5

I have multiple C files 1.c 2.c and 3.c and their correspondent 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

NB :

  • None of the c files include another header (i.e 1.c dont include 2.h and 3.h etc..).

  • All of the 3 files include a 4.h file.

  • All of the 3 files have the same Makefile.

W.draoui
  • 323
  • 1
  • 3
  • 14
  • 3
    Don't define variables in headers. There are always better alternatives. You can always use `extern`. – Eugene Sh. Jun 30 '17 at 18:28
  • `#define` is for defining macros, not variables. – Barmar Jun 30 '17 at 18:29
  • I can't use #define ? – W.draoui Jun 30 '17 at 18:30
  • declare it in one (or more) headers using `extern` keyword (without static), define it in only one cpp file (without `extern` and without `static`). Note: variable definition is like `int x`, and has nothing to do with `#define`. See https://stackoverflow.com/a/1410632/2630032 for an explanation. – Stephan Lechner Jun 30 '17 at 18:30

2 Answers2

5

If the variable in question is a constant string that will never change, you can get away with using a #define for this.

In 4.h:

#define MY_STATIC_STRING "my_string"

This will perform a text substitution in each source file anyplace you use MY_STATIC_STRING.

dbush
  • 162,826
  • 18
  • 167
  • 209
  • 1
    What if I have a function that use this static string (i.e functionX(static char* x); ) that will be accepted ? – W.draoui Jun 30 '17 at 18:48
  • Yes, the `#define` is for a string constant, so you use it anywhere a `char *` is expected. – dbush Jun 30 '17 at 18:53
3

Put this in 4.h, that all 3 include:

extern char* myGlobalVar;

This will declare the variable (just like declaring functions in header files), so the compiler does not complain when it sees myGlobalVar referenced in the other .c files (knowing that it has been declared). Then put this in one(and only 1) of the 3 files (1.c 2.c or 3.c):

char* myGlobalVar = "blah";

This defines the variable, which assigns an actual value to it (just like when you define a function in the corresponding .c file). There can be multiple declarations of an identifier (such as myGlobalVar), but only one definition. So you could write extern char* myGlobalVar; in all of the .h files, but you can only write char* myGlobalVar = "blah"; in one of the .c files.

Now you can access myGlobalVar in any of the 3 c files as long as they all include 4.h.

Felix Guo
  • 2,632
  • 12
  • 20
  • 2
    Should mention terminology here. This is "declaring" the variable in the header files, and "defining" the variable in one of the 3 .c files. – William Pursell Jun 30 '17 at 18:55