Home > Back-end >  Are #define-s in a source file local to that object?
Are #define-s in a source file local to that object?

Time:10-28

I'm unsure of the terminology, but I would like to know if in the following scenario, main.c has access to x.cs #defines:

/*x.h*/
#define ONE 1
/*x.c*/
#include "x.h"
#define TWO 2
/*main.c*/
#include "x.h"
int a = ONE;
int b = TWO;

You could just tell me to run gcc -o out main.c x.c if I want to know. But it might work, yet not be correct. This is why I am asking you. My goal is to have the #defines in x.c be local to that file, so they don't clash with any others in main.c. On the other hand, I do want #defines from x.h to be available to main.c because they need to be used when implementing the functions from x.c

Please advise

CodePudding user response:

Your two .c files are equivalent to the following:
x.c :

#define ONE 1
#define TWO 2

main.c :

#define ONE 1
int a = ONE;
int b = TWO;

Any #define in a .c file will be local to that file. This is a common practice when optimizing code, leave a #define that is exclusively used in a .c file declared in that same c file.

Edit : BUT as #defines and #includes (and many other preprocessor directives) are expanded, this is done from top to bottom. meaning that one directive can then recieve #defines from some #include that was expanded earlier.
Here's an example of what I'm saying:
a.h :

#define A 1

b.h :

#define NEW_A A 1

main.c :

#include "a.h"
#include "b.h"
#include <stdio.h>

int main() {
    printf("%i, %i\n", A, NEW_A);
    return 0;
}

Will output:

1, 2

I'd suggest reading about compilation units and preprocessor directives in C.

  •  Tags:  
  • c
  • Related