Is there a way to ignore unused undefined references?

点点圈 提交于 2019-12-01 04:48:54

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.

The problem is that your undefined function is used. The object code for Func2 has been generated, there's a reference to unexisting UndefFunc, and it goes to the linker. Compiler has no way to understand that this function will always be undefined as there are multiple translation units.

The only way to avoid compilation error is to tell linker that you don't need object code for unused functions, so that it won't try to generate assembly for this case.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!