user14248283
user14248283

Reputation:

Can I "hide" anything defined in a header file in C++

Let's say I Have a header file test.h.

#pragma once

extern uint64_t a;

void foo( uint64_t );

In my case, uint64_t is used to represent a Bitboard as a part of my chess engine
test.h
Naturally I will be using uint64_t everywhere. I wanted to create a type alias for uint64_t, as Bitboard.
So I did

using uint64_t = Bitboard;

But since this is a header file, Bitboard is now defined everywhere, since this header file is used by almost all the other files of the project.
The problem is that I only want to use this alias in test.h.

The problem

The project isn't small, and Bitboard isn't a very unique identifier, I feel a global alias like this can cause some collisions, and hence I want to strictly keep it within test.h.

Is there any way I can still use create something in a header file, and not have it leak into all the other files of my project?

Upvotes: 2

Views: 1082

Answers (3)

eerorika
eerorika

Reputation: 238311

Is there any way I can still use create something in a header file, and not have it leak into all the other files of my project?

No. Included files are included entirely. If an included file contains something, then that something will be included. Simple solution is to not put something into the header that you don't want it to contain.


using uint64_t = Bitboard;

But since this is a header file, Bitboard is now defined everywhere

That doesn't define Bitboard. That defines uint64_t - which is an identifier reserved to the language implementation in the global namespace.


The project isn't small, and Bitboard isn't a very unique identifier

Besides the solution of not defining it mentioned above, a way to deal with this is to define the name within a namespace so that its uniqueness improves.

Upvotes: 2

Kostas
Kostas

Reputation: 4176

Best you can do is use an ugly C #define

#pragma once

#define Bitboard uint64_t

extern Bitboard a;
void foo(Bitboard);

...

#undef Bitboard

Upvotes: 2

Beta
Beta

Reputation: 99094

Move it into a new header file, one that will be included only by the source files you want privy to the secret.

Upvotes: 1

Related Questions