Cannot use macro defined in header.

header.h

#define x 1000

header.cpp

1
2
3
4
5
#include "header.h"
void foo()
{
printf("%d",x); //Error
}


When I define x in header.cpp, I can use it normally. However, the strange thing is that I can use it in main.

main.cpp

1
2
3
4
5
6
#include "header.h"
void main()

{
printf("%d",x); //No error
}


Can you please explain why I cannot use macro from header file in source files. Since in my program my header file has multiple source files, I don't want to modify the macro multiple times each change.
you shouldn't be using macros. If you want to create a value that is type safe in c++, use global constants:

const int x = 1000;

#define is c, and is not type safe. The compiler will not check if the value passed is correct. Also, precompile directives are just that- they get replaced before the program gets built. Why not just create a variable that is actually part of the program?
Topic archived. No new replies allowed.