4

I've created a C header for C++ static-linked library foo.h, which looks like this:

#ifndef __FOO_H__
#define __FOO_H__

const size_t SOME_CONST = 22;

#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */

unsigned long foo();
...
void bar();

#ifdef __cplusplus
}
#endif /* __cplusplus */

#endif /* __FOO_H__ */

I wanted to put it in some namespace in other header cfoo. I've written this:

#ifndef __CFOO__
#define __CFOO__

namespace foo {
#include "foo.h"
}

#endif /* __CFOO__ */

GCC shows no errors and as I test, everything looks ok, but I am still not sure if this is a proper way to create this namespace. Can anybody confirm if this is a good way to do it, or maybe have some suggestions to do it better?

  • If it's your code, the namespace should really be in the header; it's declaring what you're making available, and the namespace is really part of that. If it's a third-party or generated header, then sure, that's a valid way of doing it. But then you'd need to be sure it's C++-safe C; otherwise you'd also have to surround the `#include` with the `extern "C"` construct. And of course, if the header `#include`s any C++ headers (with their own namespace declarations), things will break as well (because they'll get nested in your `foo`). – Zastai Nov 09 '15 at 20:00
  • 1
    Generic warning: Please do not prefix your own symbols with underscores. Symbols beginning with an underscore are reserved for the implementation by both the C and the C++ standard. – fuz Nov 09 '15 at 20:00
  • 1
    To be strictly pedantic: identifiers beginning with an underscore at global scope, starting with underscore+capitcal letter at any scope, or containing double underscore *anywhere* in your program. – Mark B Nov 09 '15 at 20:03
  • @Zastai It is my code, but for project reasons, I have to create two different headers - one C-styled with `extern "C"` and second one only for including in C++ files. The C-styled header doesn't include anything. – Dominik Murzynowski Nov 09 '15 at 20:13
  • 1
    I suppose my point would be that if it's acceptable for the "C" header to have the __cplusplus check and extern "C", it sounds like it would be equally acceptable to include a namespace declaration there as well. Otherwise, if your foo.h has only "pure" C, then having a "foo.hpp", which adds both the namespace and extern block, makes a bit more sense. – Zastai Nov 09 '15 at 20:19
  • @Zastai Thank you :) – Dominik Murzynowski Nov 09 '15 at 20:34

0 Answers0