Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

#include in middle of code

Tags:

c

header

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?

like image 988
Sunspawn Avatar asked Jan 30 '14 12:01

Sunspawn


2 Answers

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.

like image 179
Jeegar Patel Avatar answered Sep 21 '22 21:09

Jeegar Patel


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.

like image 22
haccks Avatar answered Sep 19 '22 21:09

haccks