在头文件中定义 C++ 函数是一个好习惯吗?

2021-12-07 00:00:00 function c++ header-files

我想知道将 C++ 常规函数而不是方法(类中的方法)存储在头文件中是否是一个好习惯.

I'm wondering if it's a good practice to store C++ regular functions, not methods(the ones in classes) inside header files.

示例:

#ifndef FUNCTIONS_H_INCLUDED
#define FUNCTIONS_H_INCLUDED

int add(int a, int b)
{
   return a + b;
}

#endif

并像这样使用它:

#include <iostream>
#include "Functions.h"

int main(int argc, char* args[])
{
    std::cout << add(5, 8) << std::endl;
    return 1;
}

这是一个好习惯吗?提前致谢!

Is this a good a good practice? Thanks in advance!

推荐答案

如果您想在多个源文件中使用一个函数(或者更确切地说,翻译单位),然后在头文件中放置一个函数声明(即函数原型),定义 在一个源文件中.

If you want to use a function in multiple source files (or rather, translation units), then you place a function declaration (i.e. a function prototype) in the header file, and the definition in one source file.

然后在构建时,首先将源文件编译为目标文件,然后将目标文件链接到最终的可执行文件中.

Then when you build, you first compile the source files to object files, and then you link the object files into the final executable.

示例代码:

  • 头文件

  #ifndef FUNCTIONS_H_INCLUDED
  #define FUNCTIONS_H_INCLUDED

  int add(int a, int b);  // Function prototype, its declaration

  #endif

  • 第一个源文件

  • First source file

      #include "functions.h"
    
      // Function definition
      int add(int a, int b)
      {
          return a + b;
      }
    

  • 第二个源文件

  • Second source file

      #include <iostream>
      #include "functions.h"
    
      int main()
      {
          std::cout << "add(1, 2) = " << add(1, 2) << '
    ';
      }
    

  • 您如何构建它在很大程度上取决于您的环境.如果您使用的是 IDE(如 Visual Studio、Eclipse、Xcode 等),则将所有文件放入项目中的正确位置.

    How you build it depends very much on your environment. If you are using an IDE (like Visual Studio, Eclipse, Xcode etc.) then you put all files into the project in the correct places.

    如果您在 Linux 或 OSX 中从命令行构建,那么您可以:

    If you are building from the command line in, for example, Linux or OSX, then you do:

    $ g++ -c file1.cpp
    $ g++ -c file2.cpp
    $ g++ file1.o file2.o -o my_program
    

    标志 -c 告诉编译器生成一个目标文件,并将其命名为与源文件相同的名称,但带有 .o 后缀.最后一个命令将两个目标文件链接在一起形成最终的可执行文件,并将其命名为 my_program(这就是 -o 选项所做的,告诉输出文件的名称).

    The flag -c tells the compiler to generate an object file, and name it the same as the source file but with a .o suffix. The last command links the two object files together to form the final executable, and names it my_program (that's what the -o option does, tells the name of the output file).

    相关文章