基本例子

以下示例將包含一個程式碼塊,該程式碼塊將拆分為多個原始檔,如// 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