Search code examples
clinuxgccc-preprocessorshared

Check for definition GNU C


I'm trying to find out a little bit more about how the preprocessor works in relation to shared object libraries generated by GCC on GNU/Linux.

I've been unable to find a clear, concise answer to this.

If I use preprocessor statements like:

#ifndef __OPTI_MY_VARIABLE
#define __OPTI_MY_VARIABLE 1
#endif

And I compile a shared object file with this and link to it with another program in which I declare:

#define __OPTI_MY_VARIABLE 2

Will my program then use the value 1 or 2 after compiling the main program which uses the shared object library?

If it uses the value 1, is there a way to construct the code such that it will use the value 2, for example by not using pre-processor statements? In other words, is there a way for me to declare default values unless another global variable by the same name overrides it, or must this info be passed to the function in the shared object?


Solution

  • #defines are only seen by the preprocessor. The preprocessor runs completely before the compiler. The compiler runs before linking.

    If you want to be able to override the default value "inside" your shared object, then I would suggest using a setter function, and a static global variable, e.g.:

    #define OPTI_MY_VARIABLE_DEFAULT   1
    
    static int opti_my_variable = OPTI_MY_VARIABLE_DEFAULT;
    
    ...
    
    void set_opti_my_variable(int i) { opti_my_variable = i; }
    

    Obviously, this uses a global variable, which many people frown upon...