0

In my project I have multiple header and source files. Most of these files include a header file called settings.h This file looks something like this

#ifndef EXTERNAL_H
#define EXTERNAL_H

#define processID 12
...
#endif // EXTERNAL_H

Now I noticed that if I change the processID from a define to a type such as this

int processID;

I start getting linker error. I wanted to know if there was a way for me to change the processID from a define to an int type.

3 Answers 3

2

The linker error is given by the fact that a symbol with the same name is generated in each source file that is including that header.

So solve that problem you have multiple choice but one in C++11 should be the way, which is the constexpr specifier:

constexpr int processID = 12;

Another solution would be to use static specifier but this will create a different variable with the same name in each source, only preventing clashes just because each symbol is hidden inside each source.

A third solution would be to use const int since a const value can't be modified then, regardless how many of them are generated in each source file, they would all resolve to the same value.

Sign up to request clarification or add additional context in comments.

1 Comment

@Yakk: yes, it works but I consider it a hack since an enum is meant to represent a set of finite possible values, which is not the case in this situation. Indeed I don't even use enum anymore since C++11 but enum class which avoids the problem.
1

I wanted to know if there was a way for me to change the processID from a define to an int type.

The simplest way is to convert it to a const declaration:

const int processID = 12;

Comments

1

You would need to use extern int processID; in the header, BUT you would then need to write int processID = 12; in one of the source files - this is because the extern keyword specifies that the actual object exists somewhere else, it doesn't define it. If you did not declare the int in a source file you would instead get a linker error saying the object isn't defined.

Alternatively, const or constexpr will reduce the object to a local scope.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.