这个C程序如何通过两个主要功能进行编译和运行? [英] How does this C program compile and run with two main functions?
问题描述
今天,在使用一个自定义库时,我发现了一种奇怪的行为.
静态库代码包含调试main()
函数.它不在#define
标志内.因此它也存在于图书馆中.它用于链接到包含真实main()
的另一个程序.
当它们都链接在一起时,链接器没有为main()
引发多声明错误.我想知道这怎么可能.
Today, while working with one custom library, I found a strange behavior.
A static library code contained a debug main()
function. It wasn't inside a #define
flag. So it is present in library also. And it is used link to another program which contained the real main()
.
When both of them are linked together, the linker didn't throw a multiple declaration error for main()
. I was wondering how this could happen.
为简单起见,我创建了一个示例程序来模拟相同的行为:
To make it simple, I have created a sample program which simulated the same behavior:
$ cat prog.c
#include <stdio.h>
int main()
{
printf("Main in prog.c\n");
}
$ cat static.c
#include <stdio.h>
int main()
{
printf("Main in static.c\n");
}
$ gcc -c static.c
$ ar rcs libstatic.a static.o
$ gcc prog.c -L. -lstatic -o 2main
$ gcc -L. -lstatic -o 1main
$ ./2main
Main in prog.c
$ ./1main
Main in static.c
"2main"二进制文件如何找到要执行的main
?
How does the "2main" binary find which main
to execute?
但是将它们一起编译会产生多个声明错误:
But compiling both of them together gives a multiple declaration error:
$ gcc prog.c static.o
static.o: In function `main':
static.c:(.text+0x0): multiple definition of `main'
/tmp/ccrFqgkh.o:prog.c:(.text+0x0): first defined here
collect2: ld returned 1 exit status
任何人都可以解释这种行为吗?
Can anyone please explain this behavior?
推荐答案
引用ld(1):
链接器将仅在命令行上指定的位置搜索一次存档.如果归档文件定义的符号在命令行中出现在归档文件之前的某个对象中未定义,则链接器将包括该归档文件中的相应文件.
The linker will search an archive only once, at the location where it is specified on the command line. If the archive defines a symbol which was undefined in some object which appeared before the archive on the command line, the linker will include the appropriate file(s) from the archive.
链接2main时,主符号在ld到达-lstatic之前得到解析,因为ld从prog.o拾取了它.
When linking 2main, main symbol gets resolved before ld reaches -lstatic, because ld picks it up from prog.o.
链接1main时,在到达-lstatic时确实有未定义的main,因此它将在存档中搜索main.
When linking 1main, you do have undefined main by the time it gets to -lstatic, so it searches the archive for main.
此逻辑仅适用于归档文件(静态库),不适用于常规对象. 链接prog.o和static.o时,两个对象的所有符号都会被无条件地包含,因此会出现重复的定义错误.
This logic only applies to archives (static libraries), not regular objects. When you link prog.o and static.o, all symbols from both objects are included unconditionally, so you get a duplicate definition error.
这篇关于这个C程序如何通过两个主要功能进行编译和运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!