C ++全局常量问题 [英] c++ global constants issue

查看:74
本文介绍了C ++全局常量问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们在一系列文件中定义了这些实用程序常量集。问题来自以下事实:TOO MANY文件包含这些全局常量文件,如果我们将一个常量添加到这些文件之一并尝试进行构建,则它将构建整个整个库,这将花费一个多小时。 p>

有人可以建议一种更好的方法吗?

解决方案

首先,如果您直接在标头中定义它们,我建议改而代之extern const,然后在cpp文件中定义它们:

  //在.hpp中:
extern const std: :string foo;

//在.cpp中:
const std :: string foo = FOO;

这样,至少可以在不重建的情况下更改定义。



其次,检查它们的包含位置。如果常量文件包含在低级头文件中,可以将包含文件移到cpp吗?删除它可能会降低耦合度,因此不必重建太多。



第三,分解该文件。我建议映射出您最终想要的结构,开始向新结构而不是旧文件添加新的常量。最终(当您确定拥有所需的结构时),将旧文件重构为新结构,并使旧文件包含整个结构。最后,仔细检查并删除所有旧文件,将它们指向相应的新部分。



然后,您可能会欺骗编译器不进行重建,如果头文件更改。您必须检查编译器的文档,这可能是不安全的,因此您有时还希望添加完整版本。


We have these set of "utility" constants defined in a series of file. The problem arises from the fact that TOO MANY files include these global constant files, that, if we add a constant to one of those files and try to build, it builds the whole entire library, which takes up more than an hour.

Could anyone suggest a better way for this approach? That would be greatly appreciated.

解决方案

First, if you are defining them directly in the header, I'd suggest instead delcaring them extern const, and then defining them in a cpp file:

//in .hpp:
extern const std::string foo;

//in .cpp:
const std::string foo = "FOO";

That way, at least definitions can be changed without a rebuild.

Second, examine where they are being included. If the constant file is being included in a low level header, can the include be moved to the cpp instead? Removing it might lower the coupling so it doesn't have to rebuild as much.

Third, break up that file. I'd suggest mapping out a structure you'd eventually want, start adding new constants to the new structure instead of the old file. Eventually (when you are sure you've got the structure you want), refactor the old file into the new structure, and make the old file include the entire structure. Finally, go through and remove all includes of the old file, pointing them at the appropriate new sections. That'll break up the refactoring so you don't have to do it all at once.

And fourth, you might be able to trick your compiler into not rebuilding if the header file changes. You'd have to check your compiler's documentation, and it might be unsafe, so you'd occasionally want to add full builds as well.

这篇关于C ++全局常量问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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