避免重复的符号并在头文件中保留代码 [英] Avoiding duplicate symbols and retaining code in header files

查看:112
本文介绍了避免重复的符号并在头文件中保留代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只有一个全局帮助器函数,该函数由头文件中的一堆宏使用。这样做的目的是通过简单地 #include '使用单个标头来允许宏使用(换句话说,我想将函数定义保留在标头中,避免将其放在单独的编译单元中)。但是,当应用程序 #include 将此文件放在多个编译单元中时,这会引起问题,因为出现重复符号问题。

I have a single global helper function which is used by a bunch of macros in a header file. The intention is to allow the macros to be usable by simply #include'ing the single header (in other words, I'd like to keep the function definition in the header and avoid putting it in a separate compilation unit). However, this causes problems when an application #include's this file in more than one compilation unit, as the duplicate symbols problem arises.

helper函数具有足够的特征,因此不应内联声明。

The helper function has enough characteristics in which it shouldn't be declared inline.

我四处乱逛,发现使用未命名的命名空间可以解决问题重复符号,即:

I was messing around and found that using unnamed namespaces solves the problem of duplicate symbols, i.e.:

namespace
{
    void foo(...)
    {
    }
};

#define HELPER_A foo(1, ...);
#define HELPER_B foo(2, ...);
...

此方法是否有缺点?有更好的选择吗?

Is there any downside to this approach? Are there better alternatives?

推荐答案

除非项目中有标记,否则您只能在项目中使用一个定义功能如 inline 。您可以根据需要拥有任意数量的函数声明(又称函数原型)。

You are only allowed one function definition in your project unless its marked as inline. You may have as many function declarations as you wish (aka function prototypes).

将函数定义移至.cpp文件,然后离开头文件中的声明

Move your function definition to a .cpp file and just leave the declaration in the header file

void foo(...); // no function body makes this a declaration only

,也可以将其标记为内联

inline void foo(...) { /* ... */ } 

inline 函数应该很小并且计算速度要快作为一般规则。

inline functions should be small and computationally fast as a general rule.

这篇关于避免重复的符号并在头文件中保留代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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