问题描述
最近我已经开始学习c ++。当我尝试编写头文件时,出现包含错误。这是我的代码: 首先是头文件(header.h)
#pragma once
void print(int);
然后是它的cpp文件(header.cpp)
#include "header.h"
#include <iostream>
using namespace std;
void print(int x){
cout << x << endl;
}
最后是我的主要cpp程序(main.cpp)
#include <iostream>
#include "./header.h"
using namespace std;
int main(){
int x = 123;
print(x);
}
这是错误,我不知道它在说什么orz
cd“ / Users / yianchen / Desktop / cpp实践/” && g ++ main.cpp -o main && “ /用户/ yianchen /桌面/ cpp练习/”的主要未定义符号 架构x86_64:“ print(int)”,引用自: 在main-90c620.o中的_main ld:对于体系结构x86_64铛,找不到符号:错误:链接器命令失败,退出代码为1(使用-v 参见调用)
#include "header.cpp"
工作正常,但是我不建议使用#include some_file.cpp
顺便说一句,我使用Visual Studio代码并使用代码运行器。谢谢!
解决方法
通常的用法是编译 header.cpp
,而不是将其包含在另一个.cpp
源中。然后,链接器会将这些片段放在一起。
最简单的解决方案是执行以下操作
g++ header.cpp main.cpp
这将确保header.cpp
中定义的函数与使用该函数的代码一起编译。