Under what situation is it possible for GCC to not throw an "undefined reference" link error message when trying to call made-up functions?
For example, a situation in which this C code is compiled and linked by GCC:
void function()
{
made_up_function_name();
return;
}
...even though made_up_function_name
is not present anywhere in the code (not headers, source files, declarations, nor any third party library).
Can that kind of code be accepted and compiled by GCC under certain conditions, without touching the actual code? If so, which?
Thanks.
EDIT: no previous declarations or mentions to made_up_function_name
are present anywhere else. Meaning that a grep -R
of the whole filesystem will only show that exact single line of code.
Yes, it is possible to avoid reporting undefined references - using
--unresolved-symbols
linker option.From
man ld
If
function()
is never called, it might not be included in the executable, and the function called from it is not searched for either.The "standard" algorithm according to which POSIX linkers operate leaves open the possibility that the code will compile and link without any errors. See here for details: https://stackoverflow.com/a/11894098/187690
In order to exploit that possibility the object file that contains your
function
(let's call itf.o
) should be placed into a library. That library should be mentioned in the command line of the compiler (and/or linker), but by that moment no other object file (mentioned earlier in the command line) should have made any calls tofunction
or any other function present inf.o
. Under such circumstances linker will see no reason to retrievef.o
from the library. Linker will completely ignoref.o
, completely ignorefunction
and, therefore, remain completely oblivious of the call tomade_up_function_name
. The code will compile even thoughmade_up_function_name
is not defined anywhere.If you declare the prototype of the function before using it , it shold compile. Anyway the error while linking will remain.
TL;DR It can not complain, but you don't want that. Your code will crash if you force the linker to ignore the problem. It'd be counterproductive.
Your code relies on the ancient C (pre-C99) allowing functions to be implicitly declared at their point of use. Your code is semantically equivalent to the following code:
The linker rightfully complains that the object file that contains the compiled
function()
refers to a symbol that wasn't found anywhere else. You have to fix it by providing the implementation formade_up_function_name()
or by removing the nonsensical call. That's all there's to it. No linker-fiddling involved.When you build with the linker flag
-r
or--relocatable
it will also not produce any "undefined reference" link error messages.This is because
-r
will link different objects in a new object file to be linked at a later stage.