"Undefined Refrence to Foo" 使用 G++ 编译时

"Undefined Refrence to Foo" while compiling with G++

我有三个文件:

my.cpp

#include "my.h"
#include <iostream> 

void print_foo() {
    cout << foo << '\n';
}

void print(int i) {
    cout << i << '\n'; 
}

my.h

extern int foo; 
void print_foo(); 
void print(int); 

use.cpp

#include "my.h"

int main(int argc, char *argv[]) {
    foo = 7;
    print_foo();
    print(99);
    return 0;
}

现在当我 运行 g++ my.cpp use.cpp 我得到错误

/usr/bin/ld: /tmp/ccUKJUlZ.o: in function `print_foo()':
my.cpp:(.text+0x6): undefined reference to `foo'
/usr/bin/ld: /tmp/ccN0mIhY.o: in function `main':
use.cpp:(.text+0x11): undefined reference to `foo'
collect2: error: ld returned 1 exit status

此外,如果我 运行 g++ -c my.cpp 一切正常,但是,如果我然后 运行 g++ my.o use.cpp 我得到同样的错误。

您实际上从未定义变量foo - 在use.cppmy.cpp中,您使用 foo,在 my.h 中,您 声明 它为 extern.

有关声明与定义的更多信息,请参阅 this response 的开头。您可能认为如果在 use.cpp 中的 foo = 7 行前面添加一个类型,您的问题就会得到解决;但是,您还需要做的是使 foo 成为 全局变量 而不是局部变量(当您在 main 内声明它时),因为 extern 只会 "find" 具有全局范围的变量。你可以通过在任何函数之外声明它来使变量成为全局变量(旁注 - 你应该只在你绝对时使用全局变量)。

因此,您可以通过将 use.cpp 更改为以下内容来解决您的问题:

#include "my.h"

int foo = 7;
int main(int argc, char *argv[]) {
    print_foo();
    print(99);
    return 0;
}