c++ - c++中分离头文件及其逻辑

标签 c++ g++ header-files

<分区>

请让我了解头文件在 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 的概念不是很清楚。

最佳答案

当您调用 g++ main.cpp 时,编译器将尝试编译并链接 程序,但为了链接,它缺少包含square 的定义。所以它可以根据头文件中给定的函数原型(prototype)编译main.cpp,但是不能链接。

只编译main.cpp

g++ -c main.cpp

要编译和链接完整的程序,请编写:

g++ main.cpp myfunc.cpp

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

关于c++ - c++中分离头文件及其逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48683088/

相关文章:

c++ - 未定义的标识符 - 缺少哪些头文件? - DX12

类中的 C++11 线程

c++ - 按通用引用返回

c++ - g++ 不包括库

c++ - 收到有关默认构造函数的错误,我不知道为什么 - C++

c++ - 没有返回对局部变量的引用的编译器警告

C 未知类型名称堆栈

c++ - 包括来自不同目录的头文件的问题[不是路径问题]

c++ - 类似项目中的 MessageBox 行为

c++ - `std::shared_ptr` 不应该默认使用 `std::default_delete` 吗?