简体   繁体   中英

LINKER ERROR 2005/2001 c++, visual studio

i am learning c++ and i run into a problem i cant fix.

i looked up the errors on docs.microsoft but it doesnt help me that much^^.

the problem:

i defined a struct in " main.h " with all variables i need in my program.

i included the main.h in 3 different source files.

-> Error 2005 already defined in xx.obj

--> i tried to delete the struct and make all variables extern -> another error..

next try:

i made for all x.cpp files an own header file with only the variables included (as struct with same name from main.h) i need. now i get a name conflict since all structs are named the same.

i think the fix is to give all structs different names and instantiate them with different names...

main.h

    struct hallo {
    int x1;
    .
    .
     int x;
    } h;
    void func1();
void func2();

test1.cpp

#include main.h
void func1() {h.x1 = ..;}

test2.cpp

    #include main.h
    void func2() {h.xn = ...;}

main.cpp

    #include main.h
    func1();
    func2();

2 questions: 1. is my solution right? 2. isnt there a smoother way for this? i just wanted 1 struct... :(

sorry for the bad english:D

No it's not right. Do it like this

main.h

struct hallo {
    int x1;
    ...
    int x;
};

extern hallo h;

main.cpp

#include "main.h"

hallo h;

test1.cpp

#include "main.h"

test2.cpp

#include "main.h"

In other words, extern in the header file, not extern in one (and only one) of your cpp files.

This really would be explained in any good C++ book. You should try and find one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM