Define char in header

I have multiple C files 1.c 2.c and 3.c and their corresponding headers 1.h 2.h 3.h. these files use the same static char * variable , so I want to define this variable in one header file. Is there any solution?

like: #define nameVariable valueVariable

Note:

  • None of the c files contain a different header (ie 1.c does not include 2.h and 3.h, etc.).

  • All 3 files include a 4.h file.

  • All 3 files have the same Makefile.

+3


source to share


2 answers


If the variable in question is a constant that will never change, you can avoid using it #define

for that.

At 4.h:



#define MY_STATIC_STRING "my_string"

      

This will replace the text in every source file where you use MY_STATIC_STRING

.

+2


source


Put this in 4.h that all 3 include:

extern char* myGlobalVar;

      

This will declare a variable (just like declaring functions in header files), so the compiler doesn't complain when it sees myGlobalVar

which other .c files are referencing (knowing it has been declared). Then put this in one (and only 1) of 3 files (1.c 2.c or 3.c):



char* myGlobalVar = "blah";

      

This one defines a variable that assigns the actual value to it (just like when defining a function in the corresponding .c file). There can be multiple identifier declarations (for example, myGlobalVar), but only one definition. This way you can write extern char* myGlobalVar;

in all .h files, but you can char* myGlobalVar = "blah";

only write in one of the .c files.

You can now access myGlobalVar

any of the three c files as long as they all include 4.h.

+3


source







All Articles