简体   繁体   中英

Undefined Extern Reference in Eclipse

I'm trying to compile some simple c++ code in Eclipse that compiles fine in Visual Studio.

I have the following files (renamed and simplified for clarity). Main.cpp has other boilerplate code in it for the main function and so forth, which I've omitted.

Foo.h

#ifndef FOO_H
#define FOO_H
extern Int foo;
#endif

Foo.cpp

Int foo = 0;

Main.cpp

#include "Foo.h"
void bar() {
    foo = 1;
}

When I try to compile this in Eclipse, I get the following error (omitted the long paths)

Main.o: in function bar():jni/Main.cpp:25: error: undefined reference to 'foo'
collect2: ld returned 1 exit status

If I hover my mouse over foo in Main.cpp, it shows the tooltip for it, and if I right click on it and select Open Declaration, it takes me to Foo.cpp and highlights the foo declaration. So it is clearly finding it, but failing to compile.

If I move the declaration to Main.cpp, like below, then it compiles fine.

Main.cpp

#include "Foo.h"
Int foo = 0;
void bar() {
    foo = 1;
}

So for some reason, Eclipse is not seeing the declaration when it is placed in a different cpp file to the one that is actually referencing it. Why is that, and how do I fix it? Unfortunately, moving the declaration to the Main.cpp is not possible as the extern needs to be accessed across a number of cpp files.

此错误意味着Foo.cpp的内容未链接到可执行文件(并且可能未编译)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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