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

and*_*and 3 c linker gcc

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

他们的包含文件是:

libdrm.h

#ifndef __LIBDRM_H__
#define __LIBDRM_H__

#include <pthread.h>

#endif
Run Code Online (Sandbox Code Playgroud)

libdrm.c < - 没有main()

#include <stdio.h>
#include <pthread.h>
#include "libdrm.h"
Run Code Online (Sandbox Code Playgroud)

tester-1.c < - 有teh main()

#include <stdio.h>
#include <pthread.h>
#include "libdrm.h"
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

而且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'
Run Code Online (Sandbox Code Playgroud)

所有这些函数都在libdrm.c中定义

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

miz*_*izo 11

要将.c源代码编译为目标文件,请使用GCC -c选项.然后,您可以针对所需的库将目标文件链接到可执行文件:

gcc libdrm.c -c
gcc tester-1.c -c
gcc tester-1.o libdrm.o -o tester1 -lpthread
Run Code Online (Sandbox Code Playgroud)

否则编译链接一气呵成,因为许多人都认为,工作正常了.但是,理解构建过程涉及这两个阶段是很好的.

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

  • libdrm.c单独无法生成可执行文件,因为它没有main()函数.
  • tester-1.c链接失败,因为链接器没有被告知所定义的符号libdrm.c.

使用-c选项,GCC编译和汇编源,但跳过链接,留下.o文件,可以链接到可执行文件或打包到库中.