You have a few misconceptions, it seems:
Originally Posted by
kjwilliams
For instance, In a project setting when you compile these files to produce the executable, these manifest constants are treated
like global variables. If that is how they're supposed to work , then which #define is used?
They're not treated like global variables. The preprocessor, which handles #defines, is basically a text substitution program. Everywhere that the token MYVAR is encountered, it is replaced by the value (91 or 25). You can see the output if you use GCC by using the -E flag:
Code:
$ gcc -Wall -E filea.c
<snip>
int main(void)
{
printf("MYVAR = %d\n", 91);
return 0;
}
For MSVC++, some hints as to compiler flags may be here (can't say how close this is, since I don't use MSVC++): Header Defines.
Originally Posted by
kjwilliams
which manifest constant takes precedence if both files have source code that use MYVAR?
First, you must understand what a translation unit is. Basically, when a .c file is done being preprocessed, that is the translation unit. The result of all the preprocessing, any #includes and conditional preprocessor stuff, will tell you what value gets used. If some file, filex.c, which doesn't define MYVAR, but does include fileb.h, then it uses the value in the .h file. The only problem is when a .c file both defines a constant and includes a file defining the same constant. Multiple .c files being combined, where two different values for MYVAR may come into play, happens at the linking stage. But at that point, all preprocessor stuff has been processed, so MYVAR is no more, only it's literal values exist anywhere.
As an example of the problem with defining and #including:
Code:
$ cat fileb.h
#define MYVAR 25
$ cat filea.c
#include <stdio.h>
#ifdef USE_FILEB
# include "fileb.h"
#endif
#define MYVAR 91
int main(void)
{
printf("MYVAR = %d\n", MYVAR);
return 0;
}
$ gcc -Wall -ggdb3 -o filea filea.c
$ ./filea
MYVAR = 91
$ gcc -Wall -ggdb3 -DUSE_FILEB -o filea filea.c
filea.c:7:0: warning: "MYVAR" redefined [enabled by default]
fileb.h:1:0: note: this is the location of the previous definition
That conditional #ifdef says, if the symbol USE_FILEB is defined, then process the include, otherwise don't. Notice that, if I to process the #include, I get a "redefined" error. That is, if filea.c #includes fileb.h, then it's a problem. If not, it uses it's own.