如何从C++中的另一个头文件调用函数?

tag*_*oma 4 c++ function

我有以下3个文件(1*.cpp和2*.hpp):

主程序文件:

// test.cpp

#include<iostream>
#include"first_func.hpp"
#include"sec_func.hpp"

int main()
{
    double x;
    x = 2.3;
    std::cout << sec_func(x) << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

- first_func.hpp标头:

// first_func.hpp

...

double  first_func(double x, y, x)
{

    return x + y + x;
}
Run Code Online (Sandbox Code Playgroud)

- sec_func.hpp标头:

// sec_func.hpp

...

double sec_func(double x)
{
        double a, b, c;
        a = 3.4;
        b = 3.3;
        c = 2.5;

        return first_func(a,b,c) + x;
}
Run Code Online (Sandbox Code Playgroud)

如何在sec_func.hpp文件中正确调用first_func?

Kos*_*Kos 7

对于大多数函数,实现应驻留在编译单元中,该文件将由自身编译并编译一次.

标题不是由它们自己编译*,而是由多个编译单元包含.

这就是为什么你的函数定义应该存在于编译单元(如.cpp)中,而不是在头文件中.标题应该只包含声明(即没有正文),只要足以让其他编译单元知道如何调用它们.


为了完整起见,通常需要在头文件中定义的函数(作为例外)是:

  • inline 功能
  • 模板函数**(类也)

脚注:

*标题实际上可以预先编译,但这是一个加速编译的解决方案,它不会改变它们的目的; 不要为此感到困惑.
**如果使用显式模板实例化,可以将模板函数定义放在标题之外,但这是一种罕见的情况; 关键是每个想要实例化模板的编译单元(对它应用参数)都需要有完整的定义,这就是模板函数定义也进入标题的原因.


spa*_*ver 5

将函数定义放置到.hpp文件中是一种不好的做法。您应该只在其中放置函数原型。像这样:

first_func.hpp:

double  first_func(double x, double y, double x);
Run Code Online (Sandbox Code Playgroud)

first_func.cpp:

double  first_func(double x, double y, double x)
{
    return x + y + x;
}
Run Code Online (Sandbox Code Playgroud)

第二个功能相同。

然后,无论您要调用哪里first_func,您都只需first_func.hpp在其中添加相应的内容cpp,然后编写调用即可。

因此,每个模块都由hpp所有声明和cpp定义(即主体)组成。当您需要引用此模块中的某些内容时,可以包括它hpp并使用名称(常量,变量,函数等)。

然后,您必须将所有内容链接在一起:

gcc main.cpp first_func.cpp second_func.cpp -o program
Run Code Online (Sandbox Code Playgroud)