如何在 c++ 中导入文件?以及如何成功编译它们?

How to import files in c++? and how to compile them successfully?

本文关键字:成功 编译 何成功 c++ 导入 文件      更新时间:2023-10-16

我正在尝试用c ++将我的代码分解为多个文件。我的主文件是 base.cpp我正在尝试在其中导入 foo.cpp。但它在编译过程中显示以下错误。

建筑x86_64的未定义符号: "foo((",引用自: _main在base-a3f2f3.o中 LD:在建筑x86_64中找不到符号

我的基本.cpp文件是:

#include<bits/stdc++.h>
#include "foo.h"
using namespace std; 
int main(){
foo(); 
cout<<tot<<endl;
cout<<"bye"<<endl;
}

我的foo.cpp是:

#include<bits/stdc++.h>
using namespace std ; 
void foo(){
cout<<"hello world"<<endl; 
}
int tot = 90;

我的 foo.h 文件是:

#ifndef FOO_H
#define FOO_H
int tot; 
void foo(); 
#endif 

我使用以下命令成功编译我的c ++文件: g++ -std=c++14 filename.cpp && ./a.out

我使用Mac。我的代码编辑器是VS Code。

My cpp configuaration is as follows : 
{
"configurations": [
{
"name": "Mac",
"includePath": [
"${workspaceFolder}/**"
],
"defines": [],
"macFrameworkPath": [
"/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks"
],
"compilerPath": "/usr/bin/clang",
"cStandard": "c11",
"cppStandard": "c++17",
"intelliSenseMode": "clang-x64"
}
],
"version": 4
}

谢谢。

您必须编译所有 cpp 文件:

g++ -std=c++14 base.cpp foo.cpp && ./a.out

这不是问题的一部分,但您应该避免#include<bits/stdc++.h>。它是一个实现定义的标头