C++, array declaration, templates, linker error

Posted by justik on Stack Overflow See other posts from Stack Overflow or by justik
Published on 2012-11-04T22:50:44Z Indexed on 2012/11/04 23:00 UTC
Read the original article Hit count: 163

Filed under:
|
|

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.

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 test2.obj

How and where to declare vars[] to avoid linker errors? After including

#include "test.hpp"

it is late to declare it...

© Stack Overflow or respective owner

Related posts about c++

Related posts about templates