How do I define a macro in C so that I can use the "extern" keyword on the first pass in a header file, then on subsequent passes initialize the constant variables? I'm using Visual Studio 2022 on a Windows 10 computer.
At the moment I have something like the following in my header file "images.h"
#pragma once
#include <stdio.h>
// Other #includes
typedef const unsigned char CBYTE;
typedef const int CINT;
// Other typedefs
#include "globals.h"
// Rest of the "images.h" header file.
Then in my "globals.h" file I have the following code:
#ifndef _GLOBALS_H_
#define _GLOBALS_H_
extern CBYTE gc_eod16;
extern CINT gc_stf;
#else
CBYTE gc_eod16 = 127;
CINT gc_stf = 2;
#endif
Then in the file "images.c" with the main function I have something like this:
#include "images.h"
#include "globals.h"
int main(void) {
// Code in main
return 0;
}
As I have several source files which are compiled together I need to use the "extern" keyword, and have #include "images.h" at the top of the other files.
Rather than initializing the global constants separately in the file with the main function, I wanted to put them with "extern" and initialization them in the "globals.h" file. This appears to compile OK, but it's untidy to repeat the global constants in the "globals.h" file.
My question is, is there a macro so that when "globals.h" is included for the first time, the statements:
extern CBYTE gc_eod16;
extern CINT gc_stf;
are generated, then on the next #include these are replaced by:
CBYTE gc_eod16 = 127;
CINT gc_stf = 2;
so that in the source code there is one line for each variable, i.e on the first #include "extern" is placed before the variable type and name, then on the second #include "extern" is omitted, and following the variable the string "= 127; etc. is appended?
How is this done? I would be most grateful to know.