编译错误: 对‘aio_read’未定义的引用

使用aio的时候, 出现编译问题: 对‘aio_read’未定义的引用( undefined reference to 'aio_read' ). 要如何解决 ?

  1. 确认已经include头文件 aio.h;
  2. 编译的时候, 链接librt库, 命令:
$ gcc async_demo.c -lrt

选项-l 是链接的意思, rt是glibc的实时扩展库, POSIX.1b Realtime Extensions library , 包含了对real-time的支持.
rt文件所在路径:/lib或者/usr/lib下的librt.so.1, 我的PC是在/lib/x86_64-linux-gnu目录下, 并且librt.so.1作为符号链接, 指向librt-2.27.so

如果使用某些系统调用的时候, 不可能一个个去记住链接选项. 那么, 要如何确认添加哪些链接选项呢?
可以查看man手册, 函数声明下面有提及. 可以看到调用aio_read, 需要加上链接-lrt .这样就可以通过出问题的系统调用, 来确认是否缺省了某些需要链接的选项.

$ man aio_read
...
SYNOPSIS
       #include <aio.h>

       int aio_read(struct aiocb *aiocbp);

       Link with -lrt.
...

$ man pthread_create
...
       #include <pthread.h>

       int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                          void *(*start_routine) (void *), void *arg);

       Compile and link with -pthread.
...

如果是使用Clion等IDE进行编译, 而不是终端利用gcc直接编译, 要如何添加链接库?
Clion等利用cmake进行编译的IDE, 可以修改工程目录下面的CMakeLists.txt.
如工程helloc, 在 CMakeLists.txt末尾添加target_link_libraries项, 进行链接:

add_executable(helloc main.c ...)

target_link_libraries(helloc rt)

同样的, 如果是添加支持pthread的线程库, 可以在CMakeLists.txt末尾添加:

target_link_libraries(helloc pthread)
原文地址:https://www.cnblogs.com/fortunely/p/14808689.html