【问题标题】:How to import files in c++? and how to compile them successfully?如何在 C++ 中导入文件?以及如何成功编译它们?
【发布时间】:2019-11-30 13:17:26
【问题描述】:

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

架构 x86_64 的未定义符号: “foo()”,引用自: _main in base-a3f2f3.o ld:未找到架构 x86_64 的符号

我的 base.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 文件名.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
}

谢谢。

【问题讨论】:

标签: c++ visual-studio-code


【解决方案1】:

你必须编译所有的cpp文件:

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

这不是问题的一部分,但您应该避免使用#include&lt;bits/stdc++.h&gt;。这是一个实现定义的标头

【讨论】:

  • 谢谢。有用。但是假设我想在 foo.cpp 中声明一个全局变量并在 base.cpp 中使用。这该怎么做?我收到重复符号错误。
  • @SiddharthGoyal int tot; 是一个定义,而不是一个声明。全局变量只能定义一次。要声明tot,您可以在foo.h 中声明extern int tot;,并且您必须在一个cpp 文件中定义它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-20
  • 2014-04-12
  • 1970-01-01
  • 1970-01-01
  • 2016-05-03
  • 2013-07-28
  • 1970-01-01
相关资源
最近更新 更多