<分区>
请让我了解头文件在 C++ 中的工作原理。我正在使用 osx 和 g++ 编译器。我有
主要.cpp
#include<iostream>
#include "myfunc.hpp"
using namespace std;
int main() {
square(10);
return 0;
}
myfunc.hpp
#ifndef MYFUNC_HPP_
#define MYFUNC_HPP_
/*
void square(int x) {
std::cout << x * x << std::endl;
};
*/
void square(int);
#endif // MYFUNC_HPP_
myfunc.cpp
#include<iostream>
#include "myfunc.hpp"
using namespace std;
void square(int x) {
cout << x * x << endl;
}
现在,当我尝试使用 g++ main.cpp 进行编译时,它给出了
Undefined symbols for architecture x86_64: "square(int)", referenced from: _main in main-088331.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation)
因为找不到在myfunc.cpp中定义的square的函数定义。 但是,如果我在头文件中定义了 square 函数,它就可以工作,因为现在它找到了函数定义。
我想在main.cpp中使用myfunc.cpp中定义的函数,所以我使用的是头文件myfunc.hpp。我怎样才能做到这一点?我在这里做错了什么吗?由于我是 C++ 编程的新手,可能我对 header 的概念不是很清楚。