基本例子

以下示例将包含一个代码块,该代码块将拆分为多个源文件,如// filename comments 所示。

源文件

// my_function.h

/* Note how this header contains only a declaration of a function.
 * Header functions usually do not define implementations for declarations
 * unless code must be further processed at compile time, as in templates.
 */

/* Also, usually header files include preprocessor guards so that every header
 * is never included twice.
 *
 * The guard is implemented by checking if a header-file unique preprocessor
 * token is defined, and only including the header if it hasn't been included
 * once before.
 */
#ifndef MY_FUNCTION_H
#define MY_FUNCTION_H

// global_value and my_function() will be
// recognized as the same constructs if this header is included by different files.
const int global_value = 42;
int my_function();

#endif // MY_FUNCTION_H
// my_function.cpp

/* Note how the corresponding source file for the header includes the interface  
 * defined in the header so that the compiler is aware of what the source file is 
 * implementing.
 *
 * In this case, the source file requires knowledge of the global constant
 * global_value only defined in my_function.h. Without inclusion of the header
 * file, this source file would not compile.
 */
#include "my_function.h" // or #include "my_function.hpp"
int my_function() {
  return global_value; // return 42;
}

然后,其他源文件包含头文件,这些源文件希望使用头接口定义的功能,但不需要了解其实现(因此,减少了代码耦合)。以下程序使用如上定义的头文件 my_function.h

// main.cpp

#include <iostream>       // A C++ Standard Library header.
#include "my_function.h"  // A personal header

int main(int argc, char** argv) {
  std::cout << my_function() << std::endl;
  return 0;
}

编制过程

由于头文件通常是编译过程工作流的一部分,因此使用头/源文件约定的典型编译过程通常会执行以下操作。

假设头文件和源代码文件已经在同一目录中,程序员将执行以下命令:

g++ -c my_function.cpp       # Compiles the source file my_function.cpp
                             # --> object file my_function.o

g++ main.cpp my_function.o   # Links the object file containing the 
                             # implementation of int my_function()
                             # to the compiled, object version of main.cpp
                             # and then produces the final executable a.out

或者,如果希望首先将 main.cpp 编译为目标文件,然后将目标文件链接在一起作为最后一步:

g++ -c my_function.cpp
g++ -c main.cpp

g++ main.o my_function.o