【问题标题】:GCC: How can I make this compiling and linking work?GCC:我怎样才能使这个编译和链接工作?
【发布时间】:2011-02-03 16:53:14
【问题描述】:

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

它们的包含文件是:

libdrm.h

#ifndef __LIBDRM_H__
#define __LIBDRM_H__

#include <pthread.h>

#endif

libdrm.c

#include <stdio.h>
#include <pthread.h>
#include "libdrm.h"

tester-1.c

#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

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 linker


【解决方案1】:

要将您的 .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 文件,这些文件可以链接到可执行文件或打包到库中。

【讨论】:

    【解决方案2】:
    gcc tester-1.c libdrm.c -o tester1 -l pthread
    

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

    【讨论】:

    • 或者您可以将 libdrm.c 编译为目标文件并链接它。这就是“一次性”编译在后台所做的。
    【解决方案3】:
    gcc test-1.c libdrm.c -o libdrm -l pthread
    

    【讨论】:

      猜你喜欢
      • 2012-08-21
      • 1970-01-01
      • 1970-01-01
      • 2020-09-16
      • 2016-01-31
      • 2018-01-21
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多