Search code examples
cprecompile

Switching between implementations in C precompiler


I'm fairly new to programming in C. My problem is that I have two implementations of a function and I want to be able to switch between them easily.

Right now I define the two implementations of the function as function_implementation1 and function_implementation1 in the files "funtion_implementation1.h" and "funtion_implementation2.h" respectively. To switch between them I have the following file:

#define IMPLEMENTATION1

#ifdef IMPLEMENTATION_1
    #include "funtion_implementation1.h"
    #define myFunction function_implementation1
#endif

#ifdef IMPLEMENTATION_2
    #include "funtion_implementation2.h"
    #define myFunction function_implementation2
#endif

In order to switch from one implementation to the other I just have to change the first line. This approach works, and I was satisfied with it for a while, but now it is bugging me that I have to open this file so often. I have a parameters.h file where I define all my parameters and I would rather choose which implementation to use in that file. Sadly, moving the first line to that file does not work. If I do that myFunction is not defined.

What is the best way to do this?


Solution

  • you should include your parameters file where you use alias, macros, etc:

    #include "Parameters.h"
    

    also, all your headers files should start with:

    #ifndef __FILE_H__
        #define __FILE_H__
    
    // definitions go there
    
    #endif
    

    This prevents nested include of header files