简体   繁体   中英

g++ linking to external library creates undefined references

I'm trying to build a simple program to test the use of an external library but am having trouble linking it with g++. See command/results:

user@user-Nuvo-2510VTC:~/Desktop/WDT_DIO/linux/test$ g++ -o main main.o -lwdt_dio
/usr/lib/gcc/x86_64-linux-gnu/5/../../../../lib/libwdt_dio.so: undefined reference to `sem_unlink'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../../lib/libwdt_dio.so: undefined reference to `pthread_mutexattr_settype'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../../lib/libwdt_dio.so: undefined reference to `sem_close'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../../lib/libwdt_dio.so: undefined reference to `pthread_spin_lock'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../../lib/libwdt_dio.so: undefined reference to `pthread_spin_unlock'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../../lib/libwdt_dio.so: undefined reference to `pthread_create'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../../lib/libwdt_dio.so: undefined reference to `pthread_spin_init'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../../lib/libwdt_dio.so: undefined reference to `pthread_mutexattr_init'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../../lib/libwdt_dio.so: undefined reference to `pthread_spin_destroy'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../../lib/libwdt_dio.so: undefined reference to `sem_post'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../../lib/libwdt_dio.so: undefined reference to `sem_open'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../../lib/libwdt_dio.so: undefined reference to `sem_getvalue'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../../lib/libwdt_dio.so: undefined reference to `sem_wait'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../../lib/libwdt_dio.so: undefined reference to `pthread_join'
collect2: error: ld returned 1 exit status

It looks like it isn't linking to some basic libraries that are part of the OS?

Details:

gcc --version --> 5.4.0 20160609
ldd --version --> 2.23
OS            --> Ubuntu 16.04 x64, 4.8.0-36-generic kernel

You seem to be missing a link to the pthread library. Add -pthread to your compilation command:

g++ -o main main.o -pthread -lwdt_dio

Checking the man page for sem_wait(3) shows:

Link with -pthread.

Note: sem_wait was selected randomly, all of them should specify that

If you read the errors closely it says that the undefined comes from libwdt_dio.so . It also says to which function you have an undefined reference.

In this particular case, it is the pthread library. It should probably be mentioned as a dependency in WDT lib documentation.

You can add -pthread to your g++ command if you're compiling through the command line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM