How to provide multiple options to link a function

Viewed 59

I have 3 object files :

main.o

general.o

specific.o

in main.o there is a call to function : void handle(void), general.o implement a generic functionality to handle() , specific.o might or might not have an implementation to handle() , I want to specify in my cmake that "search to link handle with specific.o if fail then try with general.o"

Is that possible ?

1 Answers

There certainly is nothing in standard C++ which allows this.

For Gcc/clang toolchain you can define handle as a weak symbol in general TU with __attribute__((weak)) and as ordinary symbol in specific.

Be very careful with this though, ensure that handle itself is not called in general. Because if it is, the call might be inlined before the linker sees anything, resulting in some code calling the general method, the rest specific. Link-time optimization might be actually more safe here.

Related