Intel® C++ Compiler
Support and discussions for creating C++ code that runs on platforms based on Intel® processors.
7694 Discussions

How to force link of unused function?

jeff_keasler
Beginner
3,628 Views

I have a function in my code I only call from the debugger. To the compiler, this function looks like dead code. Is there an attribute or pragma I can place on this function to make sure it is always liked to my application? How about for skipping the dead code elimination phase? My function is declared as a helper function in a header file because it is associated with a templated C++ class definition.

Note that I *do* have a nonsensical condition statement in my class constructors (based on the constructor arguments) that "calls" the function that I don't want to eliminate. The problem is that the compiler is apparently smart enough to know that the nonsensical condition can't occur (though I'm amazed it has enough information to figure that out), and it eliminates the call as dead code.

Thanks,
-Jeff
0 Kudos
1 Solution
Judith_W_Intel
Employee
3,628 Views

Gnu (and icc/icpc) has a used function attribute described here:

http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html

There isn't currentlyanydeclspec with this functionality.

Judy

View solution in original post

5 Replies
mecej4
Black Belt
3,628 Views
I don't see why you insist on linking in a function that is never called.

Here is a way to deceive the compiler:

file A.c:

..
int trojan=0;
..

file B.c:

extern int trojan;
extern void unusedsub(...,...);
..
if(trojan)unusedsub(arg1,arg2)
..

Even this trick may fail if the compiler is allowed to do global analysis/multi-file optimizations. In that case, you would have to set trojan equal to an expression whose value is unknown to the compiler but to you is known to be equal to zero.
kfsone
New Contributor I
3,628 Views
If you're doing this under Linux/MacOS... You could do something like this in main:
if(argc[0] == 0) debugFunction();
Judith_W_Intel
Employee
3,629 Views

Gnu (and icc/icpc) has a used function attribute described here:

http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html

There isn't currentlyanydeclspec with this functionality.

Judy
jeff_keasler
Beginner
3,628 Views

Thanks. This worked. For anyone else trying this, the attribute [ __attribute__ ((used)) ] needs to be on the function declaration rather than the definition in order to be recognized.
ILevi1
Valued Contributor I
3,628 Views
Just bear in mind that in release code you should not have such functions. Someone might find them and use them to create security vulnerability.
Reply