我想使用我在libdrm.h中定义的文件tester-1.c函数,并在libdrm.c中给出了实现。这三个文件位于同一文件夹中,并使用pthread函数。
他们的包含文件是:
libdrm.h
#ifndef __LIBDRM_H__
#define __LIBDRM_H__
#include <pthread.h>
#endif
libdrm.c&lt; - 没有main()
#include <stdio.h>
#include <pthread.h>
#include "libdrm.h"
tester-1.c&lt; - 有teh main()
#include <stdio.h>
#include <pthread.h>
#include "libdrm.h"
libdrm.c的编译错误说:
gcc libdrm.c -o libdrm -l pthread
/usr/lib/gcc/x86_64-linux-gnu/4.4.5/../../../../lib/crt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
collect2: ld returned 1 exit status
test-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命令来编译和链接这些文件?
答案 0 :(得分:11)
要将.c
来源编译为object files,请使用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编译和汇编源代码,但跳过链接,留下.o
个文件,这些文件可以链接到可执行文件或打包到库中。
答案 1 :(得分:1)
gcc tester-1.c libdrm.c -o tester1 -l pthread
您需要一次性编译所有源文件,而不是单独编译它们。或者将libdrm.c编译为库,然后在编译时将它与tester1.c链接。
答案 2 :(得分:1)
gcc test-1.c libdrm.c -o libdrm -l pthread