Solved

curious about multiple defined symbols.

Posted on 2004-09-08
2
213 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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

713 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