gpt4 book ai didi

c++ - C++头文件获取失败

转载 作者:行者123 更新时间:2023-12-02 09:47:54 25 4
gpt4 key购买 nike

最近,我开始学习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);
}
这是错误,我不知道它在说什么

cd "/Users/yianchen/Desktop/cpp practice/" && g++ main.cpp -o main &&"/Users/yianchen/Desktop/cpp practice/"main Undefined symbols forarchitecture x86_64: "print(int)", referenced from:_main in main-90c620.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v tosee invocation)


我在使用时已经寻找了一些解决方案
#include "header.cpp"
它工作正常,但我不建议使用#include some_file.cpp
顺便说一句,我使用Visual Studio代码并使用代码运行器。谢谢!

最佳答案

最简单的解决方案是执行以下操作

g++ header.cpp main.cpp
这将确保 header.cpp中定义的函数与使用它的代码一起编译。

关于c++ - C++头文件获取失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63555723/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com