GCC:如何使编译和链接工作?

GCC:如何使编译和链接工作?,c,gcc,linker,C,Gcc,Linker,我想使用我在libdrm.h中定义并在libdrm.c中给出实现的文件tester-1.c函数。这三个文件位于同一文件夹中,并使用pthread函数 他们的文件包括: libdrm.h #ifndef __LIBDRM_H__ #define __LIBDRM_H__ #include <pthread.h> #endif tester-1.c的编译器错误是: gcc tester-1.c -o tester1 -l pthread /tmp/ccMD91zU.o: In fu

我想使用我在libdrm.h中定义并在libdrm.c中给出实现的文件tester-1.c函数。这三个文件位于同一文件夹中,并使用pthread函数

他们的文件包括:

libdrm.h

#ifndef __LIBDRM_H__
#define __LIBDRM_H__

#include <pthread.h>

#endif
tester-1.c的编译器错误是:

gcc tester-1.c -o tester1 -l pthread
/tmp/ccMD91zU.o: In function `thread_1':
tester-1.c:(.text+0x12): undefined reference to `drm_lock'
tester-1.c:(.text+0x2b): undefined reference to `drm_lock'
tester-1.c:(.text+0x35): undefined reference to `drm_unlock'
tester-1.c:(.text+0x3f): undefined reference to `drm_unlock'
/tmp/ccMD91zU.o: In function `thread_2':
tester-1.c:(.text+0x57): undefined reference to `drm_lock'
tester-1.c:(.text+0x70): undefined reference to `drm_lock'
tester-1.c:(.text+0x7a): undefined reference to `drm_unlock'
tester-1.c:(.text+0x84): undefined reference to `drm_unlock'
/tmp/ccMD91zU.o: In function `main':
tester-1.c:(.text+0x98): undefined reference to `drm_setmode'
tester-1.c:(.text+0xa2): undefined reference to `drm_init'
tester-1.c:(.text+0xac): undefined reference to `drm_init'
tester-1.c:(.text+0x10e): undefined reference to `drm_destroy'
tester-1.c:(.text+0x118): undefined reference to `drm_destroy'
所有这些函数都在libdrm.c中定义


我应该使用什么gcc命令来编译和链接这些文件?

要编译
.c
源代码,请使用gcc的
-c
选项。然后,您可以根据所需的库将对象文件链接到可执行文件:

gcc libdrm.c -c
gcc tester-1.c -c
gcc tester-1.o libdrm.o -o tester1 -lpthread
正如许多其他人所建议的那样,一次完成编译和链接也很好。然而,很好地理解构建过程涉及这两个阶段

您的生成失败,因为您的翻译模块(=源文件)彼此需要符号

  • libdrm.c
    本身无法生成可执行文件,因为它没有
    main()
    函数
  • tester-1.c
    的链接失败,因为没有通知链接器在
    libdrm.c
    中定义的所需符号
使用
-c
选项,GCC编译和汇编源代码,但跳过链接,留下文件,这些文件可以链接到可执行文件或打包到库中

gcc tester-1.c libdrm.c -o tester1 -l pthread

您需要一次性编译所有源文件,而不是单独编译。或者将libdrm.c编译为库,然后在编译时将其与tester1.c链接。

为实现保留双前导下划线(以及单前导下划线后跟大写字母)。不要自己使用这样的名称,也可以将libdrm.c编译为一个对象文件并链接到该文件。这就是“一次性”编译在引擎盖下所做的。
gcc test-1.c libdrm.c -o libdrm -l pthread
gcc libdrm.c -c
gcc tester-1.c -c
gcc tester-1.o libdrm.o -o tester1 -lpthread
gcc tester-1.c libdrm.c -o tester1 -l pthread
gcc test-1.c libdrm.c -o libdrm -l pthread