gpt4 book ai didi

c - C 文件(库)与 clang 链接器的基本使用

转载 作者:太空宇宙 更新时间:2023-11-04 03:45:18 25 4
gpt4 key购买 nike

我有一个主程序:

#include <stdio.h>
extern int a;
int main (int argc, char ** argv) {
int i;
printf ("Hello %p, %p\n", & i, & a);
return 0;
}

和一个单独的文件 foo.c,其中包含我对变量 a 的定义:

int a;

如果我这样构建:

clang -c main.c foo.c
clang main.o foo.o
./a.out

一切顺利。但是,如果我执行以下操作:

ar rvs bar.a foo.o

我收到一个我不明白的警告

r - foo.o
warning: /<elided>/ranlib:
warning for library: bar.a the table of contents is empty
(no object file members in the library define global symbols)

所以我检查我的图书馆,确保我的符号在那里

nm bar.a

bar.a(foo.o):
0000000000000004 C _a

然后我做

clang main.o bar.a

出现以下错误

Undefined symbols for architecture x86_64:
"_a", referenced from:
_main in main-5121f1.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

我错过了什么?

最佳答案

我觉得麻烦的是foo.c中的int a;是一个暂定的定义。它在 nm 的输出中被标记为 C(通用)。如果您显式初始化(​​为了保持一致性,初始化为 0;为确保测试目的,初始化为某个非零值),我相信您不会有任何问题。

我不完全相信,因为在 TU 的末尾,暂定定义应该转换为定义:

ISO/IEC 9899:2011 §6.9.2 External Object Definitions

¶2 A declaration of an identifier for an object that has file scope without an initializer, andwithout a storage-class specifier or with the storage-class specifier static, constitutes atentative definition. If a translation unit contains one or more tentative definitions for anidentifier, and the translation unit contains no external definition for that identifier, thenthe behavior is exactly as if the translation unit contains a file scope declaration of thatidentifier, with the composite type as of the end of the translation unit, with an initializerequal to 0.

另见 How do I share a variable between source files in C?

关于c - C 文件(库)与 clang 链接器的基本使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25050575/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com