Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resolve undefined reference by stripping unused code

Assume we have the following C code:

void undefined_reference(void);

void bad(void) {
    undefined_reference();
}

int main(void) {}

In function bad we fall into the linker error undefined reference to 'undefined_reference', as expected. This function is not actually used anywhere in the code, though, and as such, for the execution of the program, this undefined reference doesn't matter.

Is it possible to compile this code successfully, such that bad simply gets removed as it is never called (similar to tree-shaking in JavaScript)?

like image 291
Post Self Avatar asked Mar 16 '26 15:03

Post Self


2 Answers

This function is not actually used anywhere in the code!

You know that, I know that, but the compiler doesn't. It deals with one translation unit at a time. It cannot divine out that there are no other translation units.

But main doesn't call anything, so there cannot be other translation units!

There can be code that runs before and after main (in an implementation-defined manner).

OK what about the linker? It sees the whole program!

Not really. Code can be loaded dynamically at run time (also by code that the linker cannot see).

So neither the compiler nor linker even try to find unused function by default.

On some systems it is possible to instruct the compiler and the linker to try and garbage-collect unused code (and assume a whole-program view when doing so), but this is not usually the default mode of operation.

With gcc and gnu ld, you can use these options:

gcc -ffunction-sections -Wl,--gc-sections main.c -o main

Other systems may have different ways of doing this.

like image 69
n. 1.8e9-where's-my-share m. Avatar answered Mar 18 '26 05:03

n. 1.8e9-where's-my-share m.


Many compilers (for example gcc) will compile and link it correctly if you

  1. Enable optimizations
  2. make function bad static. Otherwise, it will have external linkage.

https://godbolt.org/z/KrvfrYYdn

Another way is to add the stump version of this function (and pragma displaying warning)

like image 31
0___________ Avatar answered Mar 18 '26 03:03

0___________