Is it possible to create a header variable name "variable" in C?
other programmers,
I am new to C preprocessor and recently tried to create a generic library in C (as an exercise) and I ran into a little problem while creating header guards.
All preprocessor macros are set up so that I can include and use my headers like this:
#define TYPE int
#include "myheader.h"
#undef TYPE
#define TYPE float
#include "myheader.h"
#undef TYPE
int main(void){
//Do stuff
MyFunc_int();
//More stuff
MyFunc_float();
return 0;
}
But the problem occurs when I need to include headers in multiple files. In this case, header protectors are usually applied, but since the header can be included once - for each type - neither the usual construction nor #pragma once
can be used.
Now my question is, is it possible to create a defensive "variable" header to work with different definitions TYPE
?
source to share
If you want to include a header from different compilation units, you can split the header into the publich part that plays the role of the header and the private part that plays the role of the file *.c
, for example:
#define M_CONCAT(a, b) a##b
TYPE M_CONCAT(TYPE, _min)(TYPE a, TYPE b);
#ifdef IMPLEMENT
TYPE M_CONCAT(TYPE, _min)(TYPE a, TYPE b)
{
return (a < b) ? a : b;
}
#endif /* IMPLEMENT */
Then you can include this header from multiple files, but you must make sure that only one file defines IMPLEMENT
before including the header:
#define IMPLEMENT // only in one file
#define TYPE float
#include "myheader.h"
#undef TYPE
#define TYPE int
#include "myheader.h"
#undef TYPE
This file can be a separate module compilation myheader.c
. However, you must take care to implement the function for all types. (But the linker will tell you which types you missed.)
source to share
I suggest:
- Remove protective elements
#include
cmyheader.h
. - Create different header files for each
TYPE
.
intheader.h:
#pragma once
#define TYPE int
#include "myheader.h"
#undef TYPE
floatheader.h:
#pragma once
#define TYPE float
#include "myheader.h"
#undef TYPE
And then use:
#include "intheader.h"
#include "floatheader.h"
int main(void){
//Do stuff
MyFunc_int();
//More stuff
MyFunc_float();
return 0;
}
source to share
I think you are looking for something like this:
#if !defined HEADERGUARD && defined (TYPE==int)
#define HEADERGUARD
<stuff>
#endif
You might want to have HEADERGUARD_int and HEADERGUARD_float, depending on what you are doing in the * .h file. More traditionally people split it into two * .h files.
source to share