Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I force GCC to compile functions that are not used?

I am splitting off some of the code in my project into a separate library to be reused in another application. This new library has various functions defined but not implemented, and both my current project and the other application will implement their own versions of these functions.

I implemented these functions in my original project, but they are not called anywhere inside it. They are only called by this new library. As a result, the compiler optimizes them away, and I get linking failures. When I add a dummy call to these functions, the linking failures disappear.

Is there any way to tell GCC to compile these functions even if they're not being called?

I am compiling with gcc 4.2.2 using -O2 on SuSE linux (x86-64_linux_2.6.5_ImageSLES9SP3-3).

like image 241
Nathan Fellman Avatar asked Nov 15 '10 07:11

Nathan Fellman


3 Answers

You could try __attribute__ ((used)) - see Declaring Attributes of Functions in the gcc manual.

like image 81
Paul R Avatar answered Jun 22 '23 04:06

Paul R


Being a pragmatist, I would just put:

// Hopefully not a name collision :-)
void *xyzzy_plugh_zorkmid_3141592653589_2718281828459[] = {
    &functionToForceIn,
    &anotherFunction
};

at the file level of one of your source files (or even a brand new source file, something along the lines of forcedCompiledFunctions.c, so that it's obvious what it's for).

Because this is non-static, the compiler won't be able to take a chance that you won't need it elsewhere, so should compile it in.

like image 33
paxdiablo Avatar answered Jun 22 '23 03:06

paxdiablo


Your question lacks a few details but I'll give it a shot...

GCC generally removes functions in very few cases:

  • If they are declared static
  • In some cases (like when using -fno-implement-inlines) if they are declared inline
  • Any others I missed

I suggest using 'nm' to see what symbols are actually exported in the resulting .o files to verify this is actually the issue, and then see about any stray 'static' keywords. Not necessarily in this order...

EDIT:

BTW, with the -Wall or -Wunused-function options GCC will warn about unused functions, which will then be prime targets for removal when optimising. Watch out for

warning: ‘xxx’ defined but not used

in your compile logs.

like image 35
thkala Avatar answered Jun 22 '23 04:06

thkala