Gcc / ld: undefined reference to an unused function

I am using gcc 4.3.4 and ld 2.20.51 on Cygwin under Windows 7. Here is a simplified version of my problem:

  • foo.o contains the function foo_bar() , which calls bar() in bar.o
  • bar.o contains the function bar()
  • main.c calls functions in foo.o , but foo_bar() not part of the call chain

If I try to compile main.c and link it to foo.o, I get an undefined reference to _foo_bar from ld. As you can see from my Makefile, except below, I tried to use flags to place each function in my section and delete unused sections with the linker.

 COMPILE_CYGWIN = gcc -iquote$(INCDIR) COMPILE = $(COMPILE_CYGWIN) -g -MMD -MP -Wall -ffunction-sections -Wl,-gc-sections $(DEFINE) main_OBJECTS = main.o foo.o main.exe : $(main_OBJECTS) $(COMPILE) -o main.exe $(main_OBJECTS) 

The foo_bar() function is a short function that provides a connection between two network layers in the protocol stack. Some programs do not need this, so they will not be linked in other object files associated with the top level of the stack. This is a small feature, and it seems inappropriate to put it in your own .o file.

I do not understand why ld throws an error - nothing calls foo_bar() , so there is no need to include bar() in the final executable. An employee just told me that ld not a "smart linker", so maybe what I'm trying to do is not possible?

+4
source share
2 answers

If the linker is not located from Cyberdyne Systems , it is not possible to know exactly which functions will be called. He only knows whom they are referring to. Even the Skynet linker cannot predict what decisions will be executed at runtime or what will happen if you load the module dynamically at runtime, and this starts to call various global functions 1 .

So, if you reference in module m and refer to function f, you will need to associate any module with f.


1. This problem is related to the stop problem and has been proven undecidable .

+7
source

I hit a similar problem and I find this page: http://lists.gnu.org/archive/html/bug-gnu-utils/2004-09/msg00098.html Highligt: ​​The GNU component still works in the format. o file. Gcc pulls out foo.o and then discovers that bar () was undefined.

Better put foo_bar () in another .o file.

+2
source

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


All Articles