Solved

curious about multiple defined symbols.

Posted on 2004-09-08
2
206 Views
Last Modified: 2010-04-01
Let's say I have a header file, that is included by two different .cpp files.

//test.h
#ifndef TEST_H
#define TEST_H

int g_int;
#endif

//test1.cpp
#include "test.h"
extern int g_int;
...

//test2.cpp
#include "test.h"
extern int g_int;

I am getting the link error LNK2005: "int g_int" (?g_int@@3HA) already defined in test1.obj

Now I thought that declaring them as extern in the .cpp files would tell the compiler that the g_int variable was already declared externally.  I know that I can move the g_int declaration to the .cpp file and it will work fine.  I was just curious if there was any way at all to have a global variable in a header file.
0
Comment
Question by:lwinkenb
2 Comments
 
LVL 23

Accepted Solution

by:
brettmjohnson earned 125 total points
Comment Utility
Header files are physically included into the including source in-line,
so your construct is equivalent to:

//test1.cpp
int g_int;
extern int g_int;
...

//test2.cpp
int g_int;
extern int g_int;

You see that g_int is now defined in both test1 and test2.
Generally, the header file contains the declaration ("extern int g_int;")
while the cpp file contains the definition.  You have it backward.

0
 
LVL 5

Author Comment

by:lwinkenb
Comment Utility
Thanks a lot.
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Suggested Solutions

Article by: SunnyDark
This article's goal is to present you with an easy to use XML wrapper for C++ and also present some interesting techniques that you might use with MS C++. The reason I built this class is to ease the pain of using XML files with C++, since there is…
Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a …
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now