compiler g++ on linux
file.h has the following, int x=5;
and inside the main program file I can access "x" without declaring it
"extern x". Program compiles and runs fine....
also program compiles and runs fine with x declared as extern.
So is it necessary to declare x as extern if one get away without
declaring it extern ? What is the standard and good practice ? 10 1921
mark wrote: compiler g++ on linux
file.h has the following, int x=5; and inside the main program file I can access "x" without declaring it "extern x". Program compiles and runs fine....
That's because your 'file.h' is '#include'd into exactly one translation
unit. If you try including it into more than one translation unit (and
that's pretty much what '.h' files are for), you'll end up with multiple
definitions of 'x'. Your program will no longer compile due to ODR
violation (usually reported at linking stage).
also program compiles and runs fine with x declared as extern.
What exactly do you mean? This
extern int x = 5;
? This is also a definition. In namespace scope this is the same as the
original
int x = 5;
All I said above still applies.
So is it necessary to declare x as extern if one get away without declaring it extern ? What is the standard and good practice ?
The good practice is to put a non-defining declaration of 'x' into the
header file
extern int x; // Note: no initializer here
and put the definition into one (and only one) of the implementation files
int x = 5;
Of course, another good practice is to avoid global variables unless
they are really necessary.
--
Best regards,
Andrey Tarasevich
let me ask this simple question.
where does one put the "extern int x" statement ?
(a) In the header (.h) file
(b) or the program file (.cpp)
On 8 Jun 2004 05:09:26 -0700, ma*********@yah oo.com (mark) wrote: let me ask this simple question.
where does one put the "extern int x" statement ? (a) In the header (.h) file (b) or the program file (.cpp)
As Andrey said, put "extern int x;" in the .h file,
*and* "int x = 5;" in *one* of the .cpp files.
--
Andre Heinen
My address is "a dot heinen at europeanlink dot com"
mark wrote: let me ask this simple question.
where does one put the "extern int x" statement ? (a) In the header (.h) file
yes
(b) or the program file (.cpp)
no
mark posted: compiler g++ on linux
file.h has the following, int x=5; and inside the main program file I can access "x" without declaring it "extern x". Program compiles and runs fine....
also program compiles and runs fine with x declared as extern.
So is it necessary to declare x as extern if one get away without declaring it extern ? What is the standard and good practice ?
First of all, let's say you have a CPP file as so:
#include "blah.hpp"
int main(void)
{
some_variable = 7;
}
After the preprocessor has processed that, you'll have a translation unit:
extern int some_variable;
int main(void)
{
some_variable = 7;
}
Now, the thing here is that no variable is declared at all!! The "extern"
says "Don't actually make a variable. There's already one made somewhere
else in some other CPP file. Compile *ME*, _this_ CPP file, and then let the
linker bother with finding out where the variable was actually declared!"
So our CPP file gets compiled. Now, somewhere else, you _MUST_ have CPP file
containing:
int some_variable;
So now, the linker takes all your translation units, which the compiler has
turned into object files, and sorts it all out.
If you DON'T want a particular variable to be visible outside of your CPP
file, then:
static int some_variable;
In this case, you won't get a compile error at all, but a Link errror, the
linker can't find the variable to which your "extern" statement refers.
-JKop
Bill Seurer wrote: mark wrote:
let me ask this simple question.
where does one put the "extern int x" statement ? (a) In the header (.h) file
yes
(b) or the program file (.cpp)
no
Why can't you put an extern declaration in a .cpp file? Why do you think
it's better in a header? Shouldn't a variable be declared at the closest
practical point to its usage?
Everybody skipped the best advice, don't use globals at all unless there
is an extremely good reason, and newbie programs rarely have such
reasons.
Brian Rodenborn
Default User wrote: Bill Seurer wrote:
mark wrote:
let me ask this simple question.
where does one put the "extern int x" statement ? (a) In the header (.h) file yes
(b) or the program file (.cpp)
no
Why can't you put an extern declaration in a .cpp file?
You can, but it's better in a header file.
Why do you think it's better in a header?
Because, since the variable is being used in more than one
translation unit (otherwise it needn't be extern), putting
the extern declaration in the translation units leads to
unnecessary code duplication and the maintenance problems
that go with that.
Shouldn't a variable be declared at the closest practical point to its usage?
Sometimes.
Everybody skipped the best advice, don't use globals at all unless there is an extremely good reason, and newbie programs rarely have such reasons.
No, they didn't.
--
Regards,
Buster.
Buster wrote: Why do you think it's better in a header?
Because, since the variable is being used in more than one translation unit (otherwise it needn't be extern), putting the extern declaration in the translation units leads to unnecessary code duplication and the maintenance problems that go with that.
I still believe that it should be explicitly declared at the point of
usage.
Brian Rodenborn
Default User wrote: Buster wrote:
Why do you think it's better in a header?
Because, since the variable is being used in more than one translation unit (otherwise it needn't be extern), putting the extern declaration in the translation units leads to unnecessary code duplication and the maintenance problems that go with that.
I still believe that it should be explicitly declared at the point of usage.
That is sort of what people used to do when C first came out, "extern
X"s and function declarations were scattered throughout their code.
Guess what happens when someone changes the definition of one of them?
The declarations should all be kept in one spot. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Vijay Kumar R Zanvar |
last post by:
Hi,
Which section of C99 says that return value
of malloc(3) should not be casted?
Thanks.
--
Vijay Kumar R Zanvar
My Home Page - http://www.geocities.com/vijoeyz/
|
by: PCHOME |
last post by:
Hello! I am working on dividing a single C file into several files.
Now I encounter a problem about the global variables
and can not find a way to solve it.
All global variables and codes used to be in that single file, that
worked OK. But when I divdie that file into several ones, I
have many "invalid use of undefined type" errors.
The four files are main.c, main.h, readLP.h, and readLP.c.
In readLP.h
|
by: Kevin |
last post by:
Hi al
I have an interesting question.... I am working witha Win API this is the Function
Public Declare Function EnumJobs Lib "winspool.drv" Alias "EnumJobsA" (ByVal hPrinter As Long, ByVal FirstJob As Long, ByVal NoJobs As Long, ByVal Level As Long, pJob As Byte, ByVal cdBuf As Long, pcbNeeded As Long, pcReturned As Long) As Lon
Which I got from the API viewer that comes with VB 6. I have tried to convert it to the following
...
|
by: Al Bahr |
last post by:
H
I am try to convert C# to vb.net I don’t know what would be an equivalent statements in VB.net any help will be appreciated.
bmiColors ' RGBQUAD structs... Blue-Green-Red-Reserved, repeat..
' <summary
' Palette entry structur
' </summary
bmiColors ' RGBQUAD structs... Blue-Green-Red-Reserved, repeat..
|
by: Al Bahr |
last post by:
H
I am try to convert C# to vb.net I don’t know what would be an equivalent statements in VB.net any help will be appreciated
bmiColors ' RGBQUAD structs... Blue-Green-Red-Reserved, repeat..
' <summary
' Palette entry structur
' </summary
bmiColors ' RGBQUAD structs... Blue-Green-Red-Reserved, repeat..
| |
by: JoeC |
last post by:
I am trying to create a message box that allows you to enter a name
then display that name on a window. The program uses win32 but that is
not the issue. I want have a global buf variable. So that it can be
filled in the window then displayed in the main window.
Here is what I have
char * buf = NULL; //In my min program.
extern char * buf; // This is the section where I want buf displayed.
|
by: jchludzinski |
last post by:
I have 3 files (see below: a.h, w.c, ww.c). I would like to use a
single x (declared somewhere) which would global to both compilation
units: w.c & ww.c. No matter where I place the "extern" qualifier - it
appears to work: x is shared between w.c and ww.c. Or if I simple
don't use "extern", it works. Why? What is the correct (or simply
preferred) usage?
---John
PSI'm using gcc (GCC) 4.0.2.
|
by: Francine.Neary |
last post by:
I have a program that uses a large lookup table, provided as a large
array in the source:
static int bigtbl={123, 456,
/* etc. etc. */
9999 };
Now this table is pretty big, and having it clutter up my main source
file is quite ugly. So I'd like to put it in a separate file and
#include that.
|
by: vaclavpich |
last post by:
Hi,
I have a question on constant variables.
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
#include <cstdlib>
#include <iostream>
using namespace std;
const static char* STATIC_CONST_NAME = "Hello";
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
| |
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |