First of all, forget about using stuff starting with cv…
It is a common problem that it’s easy to use the C interface of OpenCV in a wrong way. You would probably be happier with the C++ interface where your waitKey is not written as cvWaitKey but cv::waitKey (if you omit the using namespace cv).
The undefined reference problem is your fault. The compiler needs to know where the library binaries are so you have to tell it. The easiest solution is to call it like this:
pkg-config opencv --libs --cflags
Or something more direct:
g++ main.cpp -I/path/to/opencv/include -L/path/to/opencv/libs -lopencv_core -lopencv_highgui
If you insist on using the C interface of OpenCV (which is written in C++ ;)) then you only have to #include <opencv2/legacy/legacy.hpp> and forget the others.
Next time you ask a question try to provide more information on your problem, like distribution, way you tried to compile it, etc. Fore more info: use google