将标头文件包含到标头文件中而不将其内容暴露给包含程序 [英] Including a header file into a header file without exposing it's content to the includer

查看:66
本文介绍了将标头文件包含到标头文件中而不将其内容暴露给包含程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为C API写一个c ++包装器.为此,将C-API标头包含在我自己的标头中是最方便的,但这也将标头包含在外部系统的文件中,不应将其公开给C-API.

I would like to write a c++ wrapper for a C API. for this it is most convenient to just include the C-API header in my own header, but this also includes the header into the file of the outer system, that should not be exposed to the C-API.

capi.h

enum MyFlags {
    MY_FLAG_A,
    MY_FLAG_B,
};

void FOO_bar(int flags);

cppapi.hh

cppapi.hh

#include "capi.h"

enum class MyFlags { 
    A = MY_FLAG_A, 
    B = MY_FLAG_B 
};

namespace foo {
    void bar(MyFlags flags) { 
        FOO_bar((int)flags); 
    }
}

仅用于将c命名约定转换为c ++语言功能.因此,当使用该语言的C ++变体时,我希望c_api对我的自动完成不可用,因此不会被意外使用.

it is just to translate c naming convention into c++ language features. So when using the C++ variant of the language, I would like that the c_api is not available to my auto completion and therefore not accidently used.

推荐答案

在项目命名空间中定义命名空间 detail ,并在其中包含C标头.

Define a namespace detail in your projects namespace, and include the C header there.

如果C标头未包含在C ++中,则未定义en 外部"C" -块,请执行以下操作之一:

If the C header does not define en extern "C"- block when included from C++, do one of these:

  • 用外部 extern"C" 块包装,并验证C标头(如果包含)是有效且等效的C ++.(特别注意枚举大小和内联函数).
  • 使用 #ifdef __cplusplus 使它有效并等效于C ++.
  • Wrap with an external extern "C" block and verify the C header is, if included thus, valid and equivalent C++. (Special attention to enum sizes and inline functions).
  • Make it valid and equivalent C++ using #ifdef __cplusplus.

因此,所有这些C函数都隐藏在内部的实现详细信息命名空间中,不会打扰任何人.

Thus, all those C functions are hidden in the internal implementation-detail namespace, and won't bother anyone.

namespace foo {
    namespace internal {
        extern "C" {
            #include "capi.h"
        }
    }
    // Function alias
    using bar = internal::FOO_bar;
    // Type alias
    using config_t = internal::FOO_config;
}

使用 using 选择性地将所需的那些符号添加到 FOO -命名空间中.

Selectively get those symbols you need into the FOO-namespace using using.

顺便说一句:您的转发器功能实际上应该是 inline

BTW: Your forwarder-function should really be inline!

这篇关于将标头文件包含到标头文件中而不将其内容暴露给包含程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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