为什么 vscode 在我调用两个 cpp 的函数时显示"undefined reference"?



我是C++的新手,我在《C++Primer Plus》中尝试了一个例子,复习了9.6,它由2.cpp组成,没有.h,TERMINAL说

C: \Users\SPM\AppData\Local\Temp\ccRnfRBS.o:p1.cpp:(.text+0x80(:对"another(("的未定义引用collect2.exe:错误:ld返回1退出状态

我的问题是,这个程序正确吗?一个.cpp可以在没有.h的情况下调用另一个.cpp中的函数吗?谢谢你的回答,这个问题让我痛苦了几个小时,我真的不知道该怎么解决。

//file1.cpp
#include <iostream>
using namespace std;
void other();
void another();
int x = 10;
int y;
int main()
{
cout<<x<<endl;
{
int x = 4;
cout<<x<<endl;
cout<<y<<endl;
}
other();
another();
return 0;
}
void other()
{
int y = 1;
cout<<"Other: "<<x<<", "<<y<<endl;
}
//file2.cpp
#include <iostream>
using namespace std;
extern int x;
namespace
{
int y = -4;
}
void another()
{
cout<<"another(): "<<x<<", "<<y<<endl;
}

是的,您的代码没有问题。例如,你可以通过像这样的g++成功地构建你的程序

g++ file1.cpp file2.cpp

所以问题出在您的构建定义中。