0

I would like to know how I can declare a global variable within a namespace.

In general.h I have the following code:

#include <iostream>

#pragma once

#ifndef TEST_NAMESPACE
#define TEST_NAMESPACE

namespace general
{
    int n;
}

#endif

In my program when I include general.h I have this error :

Error LNK2005 "int general::n" (? n@general@@3HA) already defined in general.obj

Rhilik
  • 25
  • 6
  • Well, if you have this ` _GEN_` - don't. Such names are reserved in C++ - you should not be creating them yourself. –  Sep 08 '19 at 19:55
  • The names you changed are still reserved - any name that starts with an underscore and an uppercase letter is reserved. –  Sep 08 '19 at 19:59
  • OK I changed the name again but obviously the problem was I should be using the extern keyword – Rhilik Sep 08 '19 at 20:14

1 Answers1

1

Use the keyword extern to declare it and define in a .cpp file.

Another solution is to use inline keyword. inline variables are possible since C++17. Learn more about them here:

So, in practical terms the (now accepted) proposal allows you to use the inline keyword to define an external linkage const namespace scope variable, or any static class data member, in a header file, so that the multiple definitions that result when that header is included in multiple translation units are OK with the linker – it just chooses one of them.

Also, some of the identifiers you use are reserved. See this for more one that:

All identifiers that begin with an underscore and either an uppercase letter or another underscore are always reserved for any use.

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93