Reputation: 155
I have a number of templatic and inline functions defined in an header file (let's call it head.h
). Currently, these functions use some global variables declared with extern
in the same header and defined somewhere in one .cpp.
Everything works fine, but I would limit global variables scope only to the header where they are defined.
In other words every other .h or .cpp that includes my head.h wouldn't be able to see such globals.
Any way to achieve this result?
Upvotes: 2
Views: 1992
Reputation: 15533
One way would be to put a class around it instead of a namespace, making all functions public static methods of that class and the global variables private static variables.
i.e.:
head.h:
class A
{
public:
template <typename T> static void MethodA(T const &value)
{
//...
}
inline static void MethodB(int a, int b)
{
// ...
}
private:
static int x;
static std::string y;
};
head.cpp:
int A::x = 0;
std::string A::y;
EDIT:
Another alternate method would be to define the globals as private static variables in a class and make all functions that are allowed to use them friend functions:
head.h:
template <typename T> void FunctionA(T const &value);
void FunctionB(int a, int b);
class Vars
{
friend template <typename T> void FunctionA(T const &value);
friend FunctionB(int a, int b);
private:
static int x;
static std::string y;
};
template <typename T> void FunctionA(T const &value)
{
// ...
// ... A::x ...
// ...
}
inline void FunctionB(int a, int b)
{
// ...
// ... A::y ...
// ...
}
head.cpp:
int A::x = 0;
std::string A::y;
Upvotes: 1
Reputation: 4147
including header files just copies the content of the header file into the including cpp/h file. That means, you cannot really distinguish whether you do something in your header file or in a cpp/h file that includes your header file.
So, variables that are defined in a header file cannot be excluded. If they are in a cpp file and you would like to forbid extern, you could use an anonymous namespace:
namespace
{
int variable;
}
Best practice, obviously, would be to not use global variables at all. It is considered bad style for several reasons like readability, hard to determine dependencies, difficulties with testing, a really bad chance of extending your software and so on. So, you might reconsider this kind of architecture for your next project if refactoring is not an option here.
Upvotes: 3
Reputation: 203
No, it is not possible. If you declare some variable as extern in a header1.h - this variable will be available in any other headers which include header1.h.
Upvotes: 0