在 C++ 中分离 header 文件及其逻辑

Separate header file and its logic in c++

请让我了解 header 文件在 C++ 中的工作方式。我正在使用 osx 和 g++ 编译器。我有

main.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的函数定义。 但是,如果我在 header 文件中定义了 square 函数,它就可以工作,因为现在它找到了函数定义。

我想在main.cpp中使用myfunc.cpp中定义的函数,所以我使用的是header文件myfunc.hpp。我怎样才能做到这一点?我在这里做错了什么吗?也许我对 headers 的概念不是很清楚,因为我是 C++ 编程的新手。

当你调用g++ main.cpp时,编译器会尝试编译和link程序,但是对于linking,它缺少包含 square 定义的源文件或目标文件。所以它可以根据头文件中给出的函数原型编译main.cpp,但它不能link。

只编译main.cpp

g++ -c main.cpp

编译和link完整的程序写:

g++ main.cpp myfunc.cpp

有关包含多个翻译单元的程序的更多详细信息,例如,this link