Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gcc/ld: undefined reference to unused function

Tags:

gcc

cygwin

ld

I'm using gcc 4.3.4 and ld 2.20.51 in Cygwin under Windows 7. Here's a simplified version of my problem:

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

If I try to compile main.c and link it to foo.o, I get an undefined reference to _foo_bar error from ld. As you can see from my Makefile except below, I've tried using flags for putting each function in its own section and having the linker discard unused sections.

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 function foo_bar() is a short function that provides a connection between two networking layers in a protocol stack. Some programs don't need it, so they won't link in the other object files related to the upper layer of the stack. It's a small function, and seems inappropriate to put it into its own .o file.

I don't understand why ld throws the error -- nothing is calling foo_bar(), so there's no need to include bar() in the final executable. A coworker has just told me that ld is not a "smart linker", so maybe what I'm trying to do isn't possible?

like image 792
tomlogic Avatar asked Apr 11 '11 17:04

tomlogic


1 Answers

Unless the linker is from Cyberdyne Systems it has no way to know exactly which functions will actually be called. It only knows which ones are referenced. Even Skynet's linker can't predict what run-time decisions will be made or what will happen if you load a module dynamically at run-time and it starts calling various global functions1.

So, if you link in module m and it references function f, you will need to link with whatever module has f.


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

like image 176
DigitalRoss Avatar answered Nov 03 '22 09:11

DigitalRoss