使用 headers 时,是否需要插入我的 cpp 文件中使用的每个函数?

When using headers, do I need to insert every function used in my cpp file?

如果使用我自己的文件:

abc.cpp abc.h

假设 abc.h 包含:

//abc.h
#ifndef ABC_H
#define ABC_H

void function1 ();

#endif

假设 abc.cpp 包含:

//abc.cpp
void function1();
void function2();

void function1(){
function2();
}

void function2(){
}

如果我想通过函数1中的代码访问函数2, 我是否仍然需要这样做:

//abc.h
#ifndef ABC_H
#define ABC_H

void function1 ();
void function2 ();

#endif   

或者我可以这样离开吗:

//abc.h
#ifndef ABC_H
#define ABC_H

void function1 ();

#endif

在此先感谢您的帮助。 安德鲁 B

C++ 中的规则是使用前声明。这意味着您必须在使用前声明函数存在。

  • 一个声明只是一个函数的签名,例如:int add(int, int);
  • 一个定义是函数的body。定义也充当声明,因此如果之前未声明,则定义 也是 声明。

这采用以下 3 种形式之一:

  • 你在header文件中声明一个函数,并在cpp文件中定义它
  • 您一次声明和定义一个函数
  • 该函数是一个实现细节,在cpp文件中声明和定义

仅使用 cpp-file 功能

这些函数在 cpp 文件之外不可见,它们定义于:

// foo.hpp

// Declaration
void foo();
// foo.cpp

// Definition
void do_some_stuff() {
    std::cout << "Hello, world!\n";
}
// Definition
void foo() {
    do_some_stuff();
}

Header-only 函数

因为C++对header文件使用文本包含,你可以在header文件中定义函数,只要它们就可以访问cpp文件中定义的函数]声明在前:

// example.hpp

// declaration comes before usage
void printMessage(); //Defined in Cpp file

void printMessage10x() {
    for(int i = 0; i < 10; i++) {
        printMessage();
    }
}
// example.cpp
void printMessage() {
    std::cout << "Hello, world!\n";
}

之所以可行,是因为 printMessage 的声明出现在 header 文件的较早位置,因此它对编译器可见。

在 header 文件中声明函数是否有用?

可以内联 header 文件中声明的函数,而不必求助于 Link-time 优化。此外,在考虑是否内联函数时,编译器可以获得更多信息。

此外,模板化 类 和函数在 header 文件中声明时最易于使用。 See this question for more information.

// min.hpp

// Calculates the minimum of two numbers of any type
template<class T>
T min(T a, T b) {
    if(a < b) 
        return a;
    else 
        return b;
}