Reputation: 137
In my main .c file, I have defined NUMBER
as:
#define NUMBER '0'
In another .c file2, I have declared it as an "extern int" variable and used it. But while compiling gcc gives the following error message:
/tmp/ccsIkxdR.o: In function `file2':
file2.c:(.text+0xfd): undefined reference to `NUMBER'
collect2: error: ld returned 1 exit status
Please suggest me a way out. Thanks in advance.
Upvotes: 2
Views: 2548
Reputation: 78903
Since your NUMBER
is of type int
, you could declare it as an enumeration constant:
enum { NUMBER = '0' };
You'd have to put that in a header file (.h) and include that header in your compilation unit (.c file).
Upvotes: 0
Reputation: 409176
When you use #define
is defines a macro for the pre-processor. This macro will only be visible in the source file you defined it in. No other source file will see this macro definition, and the pre-processor will not be able to expand the macro for you in the other source file so the compiler sees the symbol NUMBER
and it doesn't have a declaration for any such symbol.
To fix this you have two choices:
NUMBER
as a proper variable instead of a macro, and then have an extern
declaration in the other source file.Upvotes: 9
Reputation: 13356
When you #define
something (i.e create a pre-processor macro) in a C file, it works as text replacement, it's not the declaration of a variable. So, when you write #define NUMBER '0'
and write extern int NUMBER;
later, the compiler converts it to extern int '0';
before compilation, which is quite meaningless and erroneous.
If you want to define a constant and access it from elsewhere, you can write:
const int NUMBER = '0';
and
extern int NUMBER;
Upvotes: 4