繁体   English   中英

ifdef中的gcc编译函数

[英]gcc compile function in ifdef

我有这个代码

#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 -DB编译它

当我运行程序时,我看到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 -DB

Gcc 告诉我undefined reference to 'test1'为什么? 我不希望 gcc 甚至编译函数test2所以 gcc 不需要知道我使用了那个未定义的函数。

当我通过不等于A -D时,我该怎么做才能让 gcc 在test2上看不到?

函数test2仍然可以从外部模块中的函数调用,即使你在这里不调用它,所以函数的定义必须存在。

如果将函数更改为static ,使其只能从当前文件中引用并将优化增加到-O1或更高,则整个函数都被优化掉了。

默认情况下,链接器不会删除死代码。

使用: -fdata-sections -ffunction-sections -fdce- -Wl,--gc-sections -static命令行选项

你的方法有点像说“如果我不看这棵树,那棵树就不再存在了。” 这当然不是真的。

如果您不想在程序中包含某个函数,请将其删除。 (以及所有对它的引用)

#include <stdio.h>
void test1();

#ifdef A
void test2()
{
    printf("start test2\n");
    test1();
    printf("end test2\n");
}
#endif

int main (void)
{
    printf("abc\n");
    #ifdef A
        test2();
    #endif
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM