在头文件中定义C ++函数是否是一种好习惯? [英] Is it a good practice to define C++ functions inside header files?

查看:78
本文介绍了在头文件中定义C ++函数是否是一种好习惯?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道将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!

推荐答案

如果要在多个源文件中使用函数(或者翻译单元),然后放置一个函数 declaration (头文件中的函数原型,而源文件中的定义

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.

示例代码:


  • 头文件

  • Header file

  #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) << '\n';
      }
    



  • 如何构建很大程度上取决于您的环境。如果使用的是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).

    这篇关于在头文件中定义C ++函数是否是一种好习惯?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆