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?
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.
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) then
grid.h` get included.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With