简体   繁体   English

gcc错误:未定义引用***

[英]gcc error: undefined reference to ***

In my main .c file, I have defined NUMBER as: 在我的主.c文件中,我将NUMBER定义为:

#define NUMBER '0'

In another .c file2, I have declared it as an "extern int" variable and used it. 在另一个.c文件2中,我已将其声明为“extern int”变量并使用它。 But while compiling gcc gives the following error message: 但是在编译gcc时会出现以下错误消息:

/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. 提前致谢。

When you use #define is defines a macro for the pre-processor . 使用#define ,为预处理器定义一个宏。 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. 此宏仅在您定义的源文件中可见。没有其他源文件将看到此宏定义,并且预处理器将无法在其他源文件中为您扩展宏,因此编译器会看到符号NUMBER ,它没有任何此类符号的声明。

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. NUMBER定义为适当的变量而不是宏,然后在另一个源文件中使用extern声明。

When you #define something (ie create a pre-processor macro) in a C file, it works as text replacement, it's not the declaration of a variable. 当你在C文件中#define (即创建一个预处理器宏)时,它可以作为文本替换,它不是变量的声明。 So, when you write #define NUMBER '0' and write extern int NUMBER; 所以,当你写#define NUMBER '0'并写入extern int NUMBER; later, the compiler converts it to extern int '0'; 之后,编译器将其转换为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;

Since your NUMBER is of type int , you could declare it as an enumeration constant: 由于您的NUMBER类型为int ,因此可以将其声明为枚举常量:

enum { NUMBER = '0' };

You'd have to put that in a header file (.h) and include that header in your compilation unit (.c file). 您必须将它放在头文件(.h)中并在编译单元(.c文件)中包含该头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM