Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gcc error: undefined reference to ***

Tags:

c

gcc

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.

like image 279
Satadip Saha Avatar asked Jul 15 '26 07:07

Satadip Saha


1 Answers

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:

  1. Put the macro in a header file that you include in both source files.
  2. Define NUMBER as a proper variable instead of a macro, and then have an extern declaration in the other source file.
like image 142
Some programmer dude Avatar answered Jul 17 '26 20:07

Some programmer dude