开发者

visual C++ typdef struct multiple defined symbols problems

开发者 https://www.devze.com 2023-04-03 08:45 出处:网络
In Visual C++, i faced \"fatal error LNK1169: one or more multiply defined symbols found\" with below code, How can i solve the problem if i wanna include both header file in both source for the other

In Visual C++, i faced "fatal error LNK1169: one or more multiply defined symbols found" with below code, How can i solve the problem if i wanna include both header file in both source for the other functions usage?

main.cpp
========
#include main.h
#include sub.h

sub.cpp
========
#include main.h
#include sub开发者_C百科.h

sub.h
=========

typedef struct{
      char colour;
      char name;
}person;

person ssss = { red, ali};


Your problem is you are defining a variable in the header file:

person ssss = { red, ali };

One is instantiated in main.cpp and one in sub.cpp. You would be better to put an:

extern person ssss;

In the header file and then define the variable once in one of the source files. This will let both source files know it exists and both will refer to the same variable, assuming this is what you want. Like the other answers have suggested I would definitely suggest using header guards too, whilst you don't specifically need them for this example it is good practice and will save you headaches in the long run.


Having the typedef included in both source files shouldn't be a problem. The problem is that the declaration of ssss appears, via sub.h, in both files. Put it in one of the source files and declare it as external in the header to fix this. Notice that you had a link error, not a compile error -- this is because the symbol was found in more than one object file.


You should add include guards to your header files, to prevent multiple inclusion of the same header.

#ifndef SUB_H
#define SUB_H


//end of file
#endif

Another thing, why are you including main.h, into your sub.cpp? That seems wrong.


in sub.h, insert the following at the top of the file;

#pragma once


person ssss = { red, ali};

ssss is intantiated once in sub.cpp and main.cpp because of sub.h included in either of the files. Instantiation goes in source files and not the header files usually. Now when you are accessing object ssss member variables, linker is failing to access which object because they both share the same scope.

The solution is to have a single global instance ( if that is what you want ) and can be accessed across different files by external linkage.

main.cpp
========
#include main.h       // What is main.h required for ?
#include sub.h

extern person ssss;

sub.cpp
========
#include main.h       //  ?!?!
#include sub.h

person ssss = { red, ali};

sub.h
=========

typedef struct{
      char colour;
      char name;
}person;
0

精彩评论

暂无评论...
验证码 换一张
取 消