简体   繁体   English

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

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

I am trying to break my code into multiple files in c++.我正在尝试将我的代码分解为 C++ 中的多个文件。 My main file is base.cpp in which I am trying to import foo.cpp.我的主文件是 base.cpp,我试图在其中导入 foo.cpp。 But it shows the following error during compilation.但它在编译过程中显示以下错误。

Undefined symbols for architecture x86_64: "foo()", referenced from: _main in base-a3f2f3.o ld: symbol(s) not found for architecture x86_64体系结构 x86_64 的未定义符号:“foo()”,引用自:base-a3f2f3.o ld 中的_main:找不到体系结构 x86_64 的符号

My base.cpp file is:我的 base.cpp 文件是:

#include<bits/stdc++.h>
#include "foo.h"
using namespace std; 

int main(){
    foo(); 
    cout<<tot<<endl;
    cout<<"bye"<<endl;
}

My foo.cpp is:我的 foo.cpp 是:

#include<bits/stdc++.h>
using namespace std ; 

void foo(){
    cout<<"hello world"<<endl; 
}
int tot = 90;

My foo.h file is:我的 foo.h 文件是:

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

#endif 

I use the following command to compile my c++ files successfully: g++ -std=c++14 filename.cpp &&./a.out我使用以下命令成功编译了我的 C++ 文件:g++ -std=c++14 filename.cpp &&./a.out

I use Mac.我用苹果机。 My code editor is VS Code.我的代码编辑器是 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
}

Thanks.谢谢。

You have to compile all cpp files:你必须编译所有的 cpp 文件:

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

It's not part of the problem but you should avoid #include<bits/stdc++.h> .这不是问题的一部分,但您应该避免使用#include<bits/stdc++.h> It's an implementation defined header这是一个实现定义的标头

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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