How to define functions and data from another namespace, not in the global one?
Like if I have a header with some declarations:
"Header.hpp"
extern int SomeData;
int SomeFunc();
And an Implementation of it (in which I declare all the functions and global variables in an unnamed namespace in order to avoid linkage problems):
"Header.cpp"
#include "Header.hpp"
inline namespace
{
const int SomeLocalFileData = 9;
struct MyLocalStructure;
int SomeLocalFunction(MyLocalStructure *);
int ::SomeData(SomeLocalFileData);
int ::SomeFunc()
{
return SomeLocalFunction(nullptr);
}
}
The above code will fail with the following errors (using 'gcc' compiler):
error: declaration of 'SomeData' not in a namespace surrounding '::' int ::SomeData(SomeLocalFileData);
error: declaration of 'int SomeFunc()' not in a namespace surrounding '::' int ::SomeFunc()
So Is there anyway I can declare all my local file symbols to be in an anonymous namespace, in order to avoid linkage problems but in the same time to be able to define my function and data exports.
You are not allowed to define object of the global scope in your anonymous namespace.
If you want to share SomeData
and SomeFunc()
with other compilation units, you simply have to define them outside your namespace.
The anonymous namespace is meant to avoid your symbols to be shared outside their compilation unit. So if you don't want to share the symbols, define them in the anaonymous namespace. Declaring them in a header will then not make them available to other compilation units. If you watt to keep the definition in a header that is only included in this file, you could enclose the definition in an anonymous namespace in the same way.
I believe what you are trying to do in your Header.cpp
file is:
inline namespace
{
const int SomeLocalFileData = 9;
struct MyLocalStructure;
int SomeLocalFunction(MyLocalStructure *);
}
int SomeData(SomeLocalFileData);
int SomeFunc()
{
return SomeLocalFunction(nullptr);
}
Being in same translation unit and after the anonymous namespace, the definitions of SomeData
and SomeFunc
have access to the local symbols (eg SomeLocalFileData
, MyLocalStructure
and SomeLocalFunction
) defined in that anonymous namespace. Those symbols will remain hidden from other translation units.
上一篇: 外部连接和全局变量