-
August 26th, 2005, 08:51 PM
#1
variable redefinition problem again...
Dear all,
I have posted the question yesterday, and thanks for the guru to answer me, however, i still have some questions:
here is the code:
suppose I want to include a global variable a in a .h file, as follows:
// stdafx.h
////////////////////////////////////////////////////////
#ifndef _STDAFX_H_
#define _STDAFX_H_
#include <stdio.h>
int a;
#endif
////////////////////////////////////////////////////////
then in the other .h files, I include the stdafx.h:
// a.h
///////////////////////////////////////////////////////
#ifndef _AH_
#define _AH_
#include "stdafx.h"
#endif
//////////////////////////////////////////////////////
// a.cpp
#include "a.h"
...
I encounter error when I compile this code under linux platform, but there are no errors when I compile in VS.net!
Can you guys tell me what problem it is? Is it the fact that i should set some compiler options in g++ compiler?
Thanks all,
Joman
-
August 26th, 2005, 10:15 PM
#2
Re: variable redefinition problem again...
Greetings.
Declare your global variable "a" as being extern in your main header like so:
Code:
//stdafx.h
extern int a;
This will allow the compiler to see it in multiple translation units without causing an infraction. Bare in mind that you are still held to the rule of only one definition.
Regards.
Last edited by SouthernCodeMonkey; August 26th, 2005 at 10:17 PM.
Reason: Misuse of "define". Changed to "declare".
-
August 26th, 2005, 10:19 PM
#3
Re: variable redefinition problem again...
Thanks.
But why there are not errors in VS.net?
Regards,
Joman
-
August 26th, 2005, 11:06 PM
#4
Re: variable redefinition problem again...
...and you really shouldn't include stdafx.h in a header file - only in cpp files.
Hope this helps,
- Nigel
-
August 27th, 2005, 04:47 AM
#5
Re: variable redefinition problem again...
Originally Posted by jomanw
But why there are not errors in VS.net?
Who told you that there are no errors in VS?
Code:
// 1.h
int a;
// 1.cpp
#include "1.h"
void main() { a; }
// 2.cpp
#include "1.h"
void foo() { a; }
Now we've got:
D:\Temp\137>cl *.cpp
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 13.10.3077 for 80x86
Copyright (C) Microsoft Corporation 1984-2002. All rights reserved.
1.cpp
2.cpp
Generating Code...
Microsoft (R) Incremental Linker Version 7.10.3077
Copyright (C) Microsoft Corporation. All rights reserved.
/out:1.exe
1.obj
2.obj
2.obj : error LNK2005: "int a" (?a@@3HA) already defined in 1.obj
1.exe : fatal error LNK1169: one or more multiply defined symbols found
Best regards,
Igor
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|