繁体   English   中英

g ++链接器问题

[英]g++ linker problem

我试图理解C ++中的关键字extern,并编写了一段简短的代码来概述其含义。 不幸的是我做错了

bla.h

int bla = 4;

TEST.CPP

#include <iostream>

using namespace std;

int main() {
       extern int bla;
       cout << bla << endl;
}

g++ -o test bla.h test.cpp
/tmp/ccED67jz.o: In function `main':
test.cpp:(.text+0xa): undefined reference to `bla'
collect2: ld returned 1 exit status

extern ,您描述的用法仅适用于全局变量:

bla.cpp

int bla = 4;

TEST.CPP

#include <iostream>

extern int bla; // use the global from bla.cpp as a global in this file

int main(int argc, char *argv[]) {
    std::cout << bla << "\n";
    return 0;
} 

像这样使用它。

TEST.CPP

extern int bla;

int main(int argc, char** argv)
{
    cout << bla << endl;
    return 0;
}

other.cpp

int bla;

g ++ test.cpp other.cpp

基本上,extern用于使编译器将外部变量链接到另一个目标文件中。 那可能是另一个源文件,甚至是一个外部库。 它也仅适用于全局变量。

  • 永远不要在标头中定义变量(在此处应使用extern)
  • 从不声明局部extern变量,这些变量始终是全局变量,在局部声明它们会引起混乱

extern的意思是:不要在这里创建变量,它已经在其他地方存在。 “其他位置”部分表示在不同的编译单元中。

例如:

在file1.c

int x;

file2.c中

extern int x; /* x already exists in file1.c */

int main()
{
    x = 10;
}

像这样编译:

gcc file1.c file2.c

暂无
暂无

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

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