Cause link to fail if certain symbol is referenced

222 Views Asked by At

Is there a way to make linking fail if the code references a certain symbol from a library?

I seem to remember dimly that there was such a directive in the linker script language, but apparently it was not GNU LD (maybe it's a false memory).

I need it to prevent some part of a third-party library from accidentally linking into the application. If it does link, it adds some static initializers which wreak havoc at runtime (it's an embedded project so the environment is a bit quirky). I cannot change the third-party library in question. I would like to detect the error at build time. I guess I can write a post-build script that parses the map file and issues an error if it finds the offending parts, but the mentioned above [false?] memory prompts me to ascertain it can't be done using the linker alone.

I'm using the GNU GCC toolchain.

1

There are 1 best solutions below

0
On

Okay, stepping out for a lunch helped me find this (pretty obvious) solution:

/* stubs.c */

void ERROR_DO_NOT_REFERENCE_THIS_SYMBOL( void );

void Offending3rdPartyFunction( void )
{
    ERROR_DO_NOT_REFERENCE_THIS_SYMBOL();
}

Here, the symbol ERROR_DO_NOT_REFERENCE_THIS_SYMBOL is never defined. An additional source file is added to the project, with stubs like the one shown above for each function that must not be referenced. If the code does reference one of these functions, the stub will take precedence over the library-provided symbol, and the link will fail:

test.cpp:(.text._TestFunc+0x4): undefined reference to `ERROR_DO_NOT_REFERENCE_THIS_SYMBOL()'
collect2.exe: error: ld returned 1 exit status