【发布时间】:2020-01-09 16:26:36
【问题描述】:
我有这个代码
#include <stdio.h>
void test2()
{
printf("start test2\n");
printf("end test2\n");
}
void main ()
{
printf("abc\n");
#ifdef A
test2();
#endif
}
用gcc test.c -o test -static -D B编译它
当我运行程序时,我发现 test2 没有运行(很好)
但是当我运行字符串时,我可以在二进制文件中看到 end test2。为什么? gcc 不需要编译!
当我编译这段代码时
#include <stdio.h>
void test1();
void test2()
{
printf("start test2\n");
test1();
printf("end test2\n");
}
void main ()
{
printf("abc\n");
#ifdef A
test2();
#endif
}
与gcc test.c -o test -static -D B
Gcc 告诉我undefined reference to 'test1' 为什么?我不希望那个 gcc 甚至编译函数 test2 所以 gcc 不需要知道我使用了那个未定义的函数。
当我通过不等于A 的-D 时,gcc 不会在test2 上查看,我该怎么做?
【问题讨论】:
-
也用
#ifdef A包裹test2。另外,也许会出现优化。 -
How to remove unused C/C++ symbols with GCC and ld? 和 discard unused functions in GCC 的重复项以及其他可以通过搜索找到的内容
-
它只是有条件编译的调用,而不是函数本身(尽管可以优化)。