在头文件编码C ++(大部分)VS .cpp文件 [英] Coding C++ (mostly) in header files vs .cpp files

查看:362
本文介绍了在头文件编码C ++(大部分)VS .cpp文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

多年来,我一直在编码的C ++标准的方式,在头文件.HPP类声明,并在源cpp文件的函数定义。最近,我搬到了一个新的公司,其中code(由升压编码风格看似影响)完全是$ C $光盘.HPP文件,一短.cpp文件包含头文件,并创建对象/程序的二进制文件。

For years I've been coding C++ in the standard way, with class declarations in header files .hpp and the function definitions in source .cpp files. Recently I moved to a new company where the code (seemingly influenced by boost coding styles) is entirely coded in .hpp files with one short .cpp file to include the header files and create the object/program binary.

这让我思考 - 什么都写在头文件中的code,而不是写一个.HPP和放大器的优势/劣势; .cpp文件为每个对象?这是假设我们的项目不创建的通用的库,然后链接到程序二进制文件,而是每个程序的二进制从头文件(和一个源.cpp文件)的总和建成。这是在C的新趋势++?

It got me thinking - what are the strengths/weaknesses of writing your code in header files as opposed to writing a .hpp & .cpp file for each object? This assumes our project doesn't create common libraries that are then linked into the program binaries, but instead each program binary is built from the sum of the header files (and one source .cpp file). Is this a new trend in C++?

例如。模板对象需要只头,但它可能看起来是一个好主意把非模板类为标题的文件,然后只需在你的二进制文件(S)这些公共项目中的类。假设你从头创建一个新的codeBase的,这将意味着更少的连接,这可能意味着更少的链接错误和可能更快的构建。将pre-编译头机构也使用头文件加快建立时间是什么意思?或者是建立倍的时间,因为我们现在需要建立一个二进制,而不是常见的链接共享库的对象时,编译所有code?

E.g. Template objects need to be header only, but it could seem a good idea to put non-template classes into header files and then simply include these common project classes in your binary(s). Assuming you're creating a new codebase from scratch, would it mean less linking, which might mean less linking errors and possibly faster builds. Would pre-compiled headers facilities also mean using header files speeds up build time? Or are build times longer because we now need to compile all code when creating a binary rather than linking common shared library objects?

另外请注意,我们不是在这里写一个API(在这种情况下,像PIMPL方法会给我们通过隐藏实现更大的灵活性),我们正在写程序在客户站点上运行。

Also note we're not writing an API here (in which case something like the pimpl idiom would give us more flexibility by hiding implementation), we're writing programs to run on a customer site.

由于提前,

推荐答案

关闭我的头顶:


  • 执行可见(更多的是软弱的,但要看情况)

  • 无需导出到库

  • 更好的机会,编译器优化的一些$ C $的C


  • 执行可见

  • 慢的建造时间

  • 臃肿的头文件

  • 在执行一个改变都需要完全重建,具有实现文件的实现不(只编译特定文件或库)

  • 在循环依赖的情况下,你可以使用向前声明,只包括在执行文件的完整类型。如果你已经是一个头,这是不再可能。

我敢肯定还有其他的,如果我能想到的更多的,我会编辑。

I'm sure there are others, I'll edit if I can think of any more.

这篇关于在头文件编码C ++(大部分)VS .cpp文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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