Solved

curious about multiple defined symbols.

Posted on 2004-09-08
2
208 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
ID: 12009540
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
ID: 12009818
Thanks a lot.
0

Featured Post

VMware Disaster Recovery and Data Protection

In this expert guide, you’ll learn about the components of a Modern Data Center. You will use cases for the value-added capabilities of Veeam®, including combining backup and replication for VMware disaster recovery and using replication for data center migration.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
Written by John Humphreys C++ Threading and the POSIX Library This article will cover the basic information that you need to know in order to make use of the POSIX threading library available for C and C++ on UNIX and most Linux systems.   [s…
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

778 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