Jake Badlands
Jake Badlands

Reputation: 1026

How to "hide" a variable inside the header file?

The header file contains two variables. Because of the structure of my program, I have two "ld: duplicate symbol" errors. These two variables have only local significance. Is there any way of making these variables "private", so they wouldn't be seen outside of the header file even if the header file is included to another source file?

EDIT: please tell me, would it be nice if I will put the variables to the cpp file? These variables are very big arrays, defined while initializing, and take a lot of lines of code...

extern char Lookup[][3] = {  "aa", "ab", "ac", "ad", "ae", "af", ... and so on (really long)}

Upvotes: 1

Views: 2669

Answers (3)

paul23
paul23

Reputation: 9435

I'm always weary about variables which are "on the loose". I mean: they do affect something don't they? They "belong" to a class?

Shouldn't you just declare them under a class, and then declare them as static variables? (And given the syntax, probably constants too)? In that case you can simply use everything normally done with static variables (initializer lists, static initialize function etc). Seems to me much more clearer, as now your variable is tied with something.

Upvotes: 1

ouah
ouah

Reputation: 145829

Do not define variable in headers.

Use extern to declare a variable in a header without defining it.

Upvotes: 3

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272487

The solution is to not define variables in your header file.

If you absolutely must share variables between internal source files (and I recommend that you don't), then you should do the following:

  1. Create an "internal.h".
  2. Declare your variable extern in that header file.
  3. Include "internal.h" in both your internal source files.
  4. Define the variable in one or other internal source files.

The variable is now hidden from the outside world. (It's probably still visible in your object files, but you can use platform-specific trickery to strip it.)

Upvotes: 6

Related Questions