Navjot Singh
Navjot Singh

Reputation: 696

Linkage error for a header containing const variables and included in multiple files?

I am writing code for testing in which I have a TestUtil.h which defines two constants and some functions. I have implementation of this header file as TestUtil.cpp and there is third file ActualTests.cpp in which I am writing the actual tests. The TestUtil.h and TestUtil.cpp are just helper files to write concise tests.

I am having nested namespaces and the TestUtil.h looks like this:

namespace SNMPSubAgentTesting {

  namespace MibDataReaderTesting {

     const wchar_t* TEST_MUTEX_NAME = L"TestMutex";

     const wchar_t* TEST_MEMORY_NAME = L"TestMemory";

   //some functions 
   } 
}

In the implementation TestUtil.cpp I include the above header file and give implementations:

#include "TestUtil.h"

 namespace SNMPSubAgentTesting {

  namespace MibDataReaderTesting {
     //implementations
  }
}

In the third file ActualTests.cpp I again include the TestUtil.h in order to use the util functions:

#include "TestUtil.h"

 namespace SNMPSubAgentTesting {

  namespace MibDataReaderTesting {

     //Test class and tests
  }
}

The compiler gives a linkage error and says that the two const variables in TestUtil.h are already defined in TestUtil.cpp and hence ActualTests.cpp cannot be compiled. Since const variables are internally linked and we can include the header containing const variables in multiple files without linking errors, why does it not link in my case? Is it because of nested namespaces?

EDIT: I am using the Microsoft Unit Test framework for testing. The const variables are in MibDataReaderTesting namespace and not in global namespace.

I have header files in my source code which are included in multiple files and have const variables in them. No error in this case but for the testing case it gives error. Only difference b/w source and test code is testing framework and nested namespaces

Upvotes: 2

Views: 497

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409166

As mentioned in this internal linkage reference const qualified names have internal linkage.

The problem is that your names are not const qualified. The const is for the data the pointers are pointing to, not for the variables themselves.

You need to add a const in the correct place:

const wchar_t* const TEST_MUTEX_NAME = L"TestMutex";
//             ^^^^^
// Make TEST_MUTEX_NAME itself constant

Upvotes: 3

Related Questions