【问题标题】:gcc compile function in ifdefifdef中的gcc编译函数
【发布时间】: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 上查看,我该怎么做?

【问题讨论】:

标签: c gcc ifdefine


【解决方案1】:

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

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

【讨论】:

  • static 使这个函数只对这个文件可用,但是我想从另一个文件调用test2,所以我在寻找另一个解决方案
【解决方案2】:

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

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

【讨论】:

  • -Wl ____________________
  • 谢谢!那工作〜请解释一下这个解决方案吗? fdata-sectionsffuntion-sections 将每个功能分开到另一个部分,-Wl,--gc-sections 只是删除未使用的部分?为什么现在链接器没有搜索 test1 ? ,顺便说一句,字符串end test2 仍然包含在最终二进制文件中
  • 它从输出文件中删除“死代码”和数据。\
  • 唯一的问题是在 GMU 站点我看到When you specify these options, the assembler and linker create larger object and executable files and are also slower。有没有不减慢代码速度,让解决方案文件变大的解决方案??
  • 它可能会增加静态库的大小,但不会增加可执行文件的大小。至少在我使用的平台上。我不知道为什么他们会考虑执行时间,因为它会完全相同。
【解决方案3】:

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

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

#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
}

【讨论】:

    猜你喜欢
    • 2013-07-19
    • 1970-01-01
    • 2013-07-22
    • 2016-10-16
    • 1970-01-01
    • 2016-12-09
    • 2010-11-17
    • 2016-02-17
    • 1970-01-01
    相关资源
    最近更新 更多