c++ linking failed with undefined reference to lib

2019-08-30 11:24发布

问题:

Just getting started with multithreading using boost threads; I have a Hello World type program which fails during linking to the thread library. The following is the terminal window output:

 g++ -Wall -I/usr/include HelloWorld.cpp -L/usr/local/lib -pthread -lboost_thread -lrt -lboost_system
/tmp/ccTKHnfd.o: In function `main':
HelloWorld.cpp:(.text+0x4a): undefined reference to `boost::thread::join()'
HelloWorld.cpp:(.text+0x5b): undefined reference to `boost::thread::~thread()'
HelloWorld.cpp:(.text+0x70): undefined reference to `boost::thread::~thread()'
/tmp/ccTKHnfd.o: In function `boost::thread::thread<void (*)()>(void (*)(), boost::disable_if<boost::is_convertible<void (*&)(), boost::detail::thread_move_t<void (*)()> >, boost::thread::dummy*>::type)':
HelloWorld.cpp: (.text._ZN5boost6threadC2IPFvvEEET_NS_10disable_ifINS_14is_convertibleIRS4_NS_6detail13thread_move_tIS4_EEEEPNS0_5dummyEE4typeE[_ZN5boost6threadC5IPFvvEEET_NS_10disable_ifINS_14is_convertibleIRS4_NS_6detail13thread_move_tIS4_EEEEPNS0_5dummyEE4typeE]+0x23): undefined reference to `boost::thread::start_thread()'
collect2: ld returned 1 exit status

I installed boost dev libraries 1.48 using aptitude and believe I am using all the right flags for the compiler. What am I missing? My gcc is 4.6.3. Thanks in advance for your help

回答1:

Probably you'll need to append "-mt" suffix to the lib flags: e.g. -lboost_thread-mt You can double check your boost library path.



回答2:

Looks like you can't find libboost_thread.so or libboost_thread.a. What is actually there in your /usr/local/lib? You can do

ls /usr/local/lib | grep thread. If you don't see libboost_thread.so or libboost_thread.a, then that explains why you have the undefined reference - the object implementing these functions isn't actually there.

Additionally, if you don't see libboost_thread.so but you do see libboost_thread.so.3.6 or something (which denotes a specific version), then you can do one of two things: either link to that directly or create a symbolic link (i.e. sudo ln -s /usr/local/lib/libboost_thread.so.3.6 /usr/local/lib/libboost_thread.so)