#include in the middle of the code

I would like to conditionally include the header file in my program. Is it possible and, if so, how can I do this?

My idea is to do something like this:

switch(opt) { case 0: { #include "matrix.h" break; } case 1: { #include "grid.h" break; } } 

This is how VS did it when I wrote it. Right?

+6
source share
3 answers

At compile time, you may have bit control for conditionally including the header file

 #ifdef MAGIC #include "matrix.h" #else #include "grid.h" #endif 

at compile time

 gcc -D MAGIC=1 file.c 

or

 gcc file.c 

But at runtime, conditional inclusion of the header file is not possible.

This means your pseudo code is showing.

+10
source

I would like to conditionally include the header file in my program. Is it possible, and if so, how can I do this?

Yes it is possible.
The C preprocessor already has directives that support conditional compilation. Better to use

 #ifndef expr #include "matrix.h" #else #include "grid.h" #endif 

If expr not defined, then matrix.h included otherwise, if it is defined ( #define expr ) then grid.h` is included.

+3
source

These are two different things. #include is a preprocessor directive that is processed at compile time . swicth is the C keyword that runs at run time .

So, you can use conditional preprocessors to choose which file to include:

 #ifdef MATRIX #include "matrix.h" #else #include "grid.h" #endif 

Or you can also include both, because it usually doesn't matter if you include a useless header file.

 #include "matrix.h" #include "grid.h" switch(opt) { case 0: /* Do something with matrix functions */ break; case 1: /* Do something with grid functions */ break; } 
+1
source

All Articles