Cause link to fail if certain symbol is referenced

爱⌒轻易说出口 提交于 2019-12-11 16:46:32

问题


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:


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


来源:https://stackoverflow.com/questions/26905841/cause-link-to-fail-if-certain-symbol-is-referenced

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!