I have a few commonly used macros that are universally needed in just about every C file I write. Currently I am copying them into each file I need them in. This is likely a bad idea because I'm eventually going to need to change one of them and then I'll end up with inconsistently defined macros between files.
Is there a way to essentially make a header file for macros? I tried to make a header with all my macros in it and include that, but I still get compiler warnings.
UPDATE: The specific warnings I get are implicit declarations of functions such as V4 from the second example.
An example:
file1.c:
#define COMMON_NUMBER 1
file2.c:
#define COMMON_NUMBER 1
//...
fileN.c:
#define COMMON_NUMBER 1
//Oh wait, it should have been 2 all along..... *facepalm*
A better example:
file1.c:
#include "usefulmacros.h"
char* prog;
int optv;
int main(){
prog = strdup(argv[0]);
optv = 4; // This would be parsed from # of "-v" in argv[]
return 0;
}
void functionA(){
int dumberror = 1;
V4("This is a fairly verbose error: %d",dumberror);
}
file2.c:
#include "usefulmacros.h"
extern char* prog;
extern int optv;
void functionB(){
int differror = 2;
V4("This is a different error: %d",differror);
}
usefulmacros.h:
#ifndef USEFULMACROS
#define V4(str, ...) if(optv >= 4){printf("%s: "str,prog,__VA_ARGS__);}
#endif
#ifndef COMMON_INCLUDE_FILE
#define COMMON_INCLUDE_FILE
#define COMMON_NUMBER 1
#define OTHER_COMMON 2
#endif
In C, where macros are a little more pervasive than C++ where you'd want to do it with a static global, the above mechanism is fairly common. You put include guards around the body of the file, and define your commons there.. This is essentially what config.h
ends up being with autoconf.. So nobody can say this isn't a standard mechanism for C code.
Just include common.h in any files that need it, done deal.
You should most definitely put your common macros in a single header for your entire project: code duplication is a dangerous thing that makes your maintenance costs go through the roof.
The warnings that you see may have to do with including the same header multiple times. You need to use include guards to avoid them.
EDIT (in response to the question update)
Your implementation of include guards is missing #define USEFULMACROS
. It should be as follows:
//usefulmacros.h
#ifndef USEFULMACROS
#define USEFULMACROS
#define V4(str, ...) if(optv >= 4){printf("%s: "str,prog,__VA_ARGS__);}
#endif
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