有没有办法忽略未使用的未定义的引用? [英] Is there a way to ignore unused undefined references?

查看:146
本文介绍了有没有办法忽略未使用的未定义的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个源文件 - UndefErr.cpp

  #include  ; 

void UndefFunc();
void Func2(){UndefFunc();}

void Func1(){printf(Hi\\\
);}

main.cpp

  void Func1(); 

int main(){
Func1();
返回0;

正如您在 UndefErr.cpp 中看到的那样,使用未定义的 UndefFunc()来触发一个错误。但是主函数并不关心 Func2()!根据相关问题,我可以通过一个选项 - -unresolved-symbols = ignore-in-object-files 到链接器,但我想要一个不同的东西。我需要一个链接器来知道未定义的函数是否在某处使用,然后才会失败。



提出这样一个奇怪问题的原因是,我试图使用 lwIP ,它很难理解它的所有依赖关系(我只需要TCP / IP),我无法在互联网上找到教程。所以我认为我可以分别编译大多数(或全部) .c文件,并编写一些简单的测试以查看它的功能。但是这种方法在未定义的引用上发生了变化,其中大部分可能与用例无关。使用Gcc 4.8.2我使用 设法将代码无错地链接到以下内容:

  $ g ++ -c main.cpp -O3 -flto 
$ g ++ -c UndefErr.cpp -O3 -flto
$ g ++ main.o UndefErr.o -flto -O3 -o out

我知道 -flto 会使链接器的行为如同 -fwhole-program 通过了,整个事情是一个单一的编制单位。根据手册, -fwhole-program 对应于 static 对函数的正确使用,所以允许未使用的函数将从输出中消除(即,您确保编译器所有函数不会被其他代码使用,可能是动态加载的,并且您为用户保证的唯一入口点是 main() )。



我不得不添加 -O3 ,我不确定为什么,但编译器对检查函数和消除死代码不感兴趣。


Suppose I have two source files — UndefErr.cpp:

#include <cstdio>

void UndefFunc();
void Func2(){UndefFunc();}

void Func1(){printf("Hi\n");}

And the main.cpp:

void Func1();

int main(){
    Func1();
    return 0;
}

As you see in the UndefErr.cpp the Func2() going to trigger an error, for it using the undefined UndefFunc(). However the main function doesn't care about the Func2()! According to a relevant question I could pass an option --unresolved-symbols=ignore-in-object-files to the linker, but I want a kinda different thing. I need a linker to know if the undefined functions used somewhere, and only then fail.

The reason for asking such a strange question is that I'm trying to use a lwIP, and it is hard to understand all of its dependencies (I only need TCP/IP), and I can't find tutorials on the internet. So I thought I could compile most (or all) the .c files separately, and write some simple tests to see what it does. But this approach stumbles upon "undefined references", most of them probably irrelevant to the usecase.

解决方案

With Gcc 4.8.2 I managed to link the code without errors with the following:

$ g++ -c main.cpp -O3 -flto
$ g++ -c UndefErr.cpp -O3 -flto
$ g++ main.o UndefErr.o -flto -O3 -o out

I know -flto will make the linker behave as if -fwhole-program was passed and the whole thing was a single compilation unit. And -fwhole-program, according to the manual, corresponds to the proper usage of static on functions, so allowing the unused function to be eliminated from the output (i.e. you assure the compiler all your functions will not be used by some other code, possibly dynamically loaded, and the only entry point you guarantee for your users is main()).

I had to add -O3, I am not sure why exactly, but the compiler was not very interested in inspecting the functions and eliminating dead code without it.

这篇关于有没有办法忽略未使用的未定义的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆