Is there a way to ignore unused undefined links?

Suppose I have two source files: UndefErr.cpp:

#include <cstdio> void UndefFunc(); void Func2(){UndefFunc();} void Func1(){printf("Hi\n");} 

And main.cpp:

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

As you see in UndefErr.cpp Func2() , to cause an error, it uses undefined UndefFunc() . However, the main function does not care about Func2() ! According to the relevant question, I could pass the option -unresolved-symbols = ignore-in-object-files to the linker, but I need another thing. I need a linker to find out if undefined functions are used somewhere, and only then crash.

The reason to ask such a strange question is that I am trying to use lwIP , and it is difficult to understand all its dependencies (I only need TCP / IP), and I can not find tutorials on the Internet. So I thought that I could compile most (or all) .c files separately and write some simple tests to see what it does. But this approach runs into "undefined links", most of which are probably unrelated to usecase.

+6
source share
2 answers

With Gcc 4.8.2, I managed to associate 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 that -flto will cause the linker to behave as if -fwhole-program passed, and all this was a single compilation unit. And -fwhole-program , according to the manual, corresponds to the correct use of static functions for functions, therefore excluding an unused function from the output (i.e. you guarantee the compiler that all your functions will not be used by any other code, is possibly dynamically loaded, and the only entry point you guarantee for your users is main() ).

I had to add -O3 , I don’t know exactly why, but the compiler was not very interested in checking functions and eliminating dead code without it.

+4
source

The problem is that your undefined function is being used . Created object code for Func2 , there is a link to the unused UndefFunc , and it goes to the linker. The compiler cannot understand that this function will always be undefined, since there are several translation units.

The only way to avoid a compilation error is to tell the linker that you do not need object code for unused functions, so it will not try to create an assembly for this case.

+3
source

Source: https://habr.com/ru/post/970696/


All Articles