There is a linker error in my SW. I am using the following structure based on h, hpp, cpp files. Some classes are templatized, some not, some have function templates. The SW contains hundreds of included classes…
Declaration:
test.h
#ifndef TEST_H
#define TEST_H
class Test
{
public:
template <typename T>
void foo1();
void foo2 ();
};
#include "test.hpp"
#endif
Definition:
test.hpp
#ifndef TEST_HPP
#define TEST_HPP
template <typename T>
void Test::foo1() {}
inline void Test::foo2() {} //or in cpp file
#endif
CPP file:
test.cpp
#include "test.h"
void Test::foo2() {} //or in hpp file as inline
I have the following problem. The variable vars[] is declared in my h file
test.h
#ifndef TEST_H
#define TEST_H
char *vars[] = { "first", "second"...};
class Test
{
public: void foo();
};
#include "test.hpp"
#endif
and used as a local variable inside foo() method defined in hpp file as inline.
test.hpp
#ifndef TEST_HPP
#define TEST_HPP
inline void Test::foo() {
char *var = vars[0]; //A Linker Error
}
#endif
However, the following linker error occurs:
Error 745 error LNK2005: "char * * vars" (?vars@@3PAPADA) already defined in main.obj
How and where to declare vars[] to avoid linker errors? After including
#include "test.hpp"
it is late to declare it…
As I wrote, the software contains a lot of cpp, and hpp files included each other (all includes have been checked). It is not possible to send the whole example…
The main.obj represents a file which contains the main class.
Declare
varsin the header with extern linkageand define it in exactly one source file
Note the
const, the conversion from string literals tochar*is deprecated. The way you have it now, you’re violationg the One definition rule (You’re redefiningvarsin every translation unit your header is included in).