Sunspawn
Sunspawn

Reputation: 837

#include in middle of code

I would like to make a conditional inclusion of a header file in my program. Is it possible and, if yes, how do I do it?

My idea is to do something like this:

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

That is how VS did it when I wrote it. Is it right?

Upvotes: 6

Views: 1400

Answers (3)

haccks
haccks

Reputation: 106012

I would like to make a conditional inclusion of a header file in my program. Is it possible and, if yes, how do I do it?

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

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

If expr has not been defined, then matrix.h get included otherwise if it is defined (#define expr) thengrid.h` get included.

Upvotes: 3

Jeegar Patel
Jeegar Patel

Reputation: 27210

At compile time you can have bit control of conditional inclusion of a 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 run-time conditional inclusion of a header file is not possible.

It means what your pseudo code is showing is not possible.

Upvotes: 10

jmlemetayer
jmlemetayer

Reputation: 4952

This is 2 different things. The #include is a preprocessor directive which is processed at compilation time. The swicth is a C keyword which is proccessed at execution time.

So, you can use the conditional preprocessor directives in order to choose what file to include:

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

Or you can also include both, because normally, it does not matter if you include 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;
}

Upvotes: 1

Related Questions