473,770 Members | 1,870 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

extern char and include practices

atv
Alright, i have some questions concerning include files en global
variables.I hope someone is willing to answer these.

1).Why is it that if i define a global variable in a file, say main.c,
and i have also other functions defined in that file, i can use the
global in all functions, but once i split up the rest of the function in
other files, i cannot use the global? Isn't that strange, all the files
compiled should be treated as one program right ?

Or should i always define the variables somewhere, say main.c, and use
extern char var[]; in the other source files?

2). What is the proper way to use include files? If i split my code and
functions up in different files, what is the normal way of using
includes. Do you, each time for a new file, have a list of the includes
setup again in that file, or ?

Right now, i have a method i saw from some other code, by defining all
the include headers in one include.h, and using that include for all
files. That way you only have to include a file once, saves a lot of
typing. Is this a correct way or a very bad way of doing things.

3). I have code that is split up in multiple files. The main function
sits in main.c, and calls for example, a logging function, which sits
in log.c. Now log() needs to remember the amount of lines it has
written. How would i do this ? Declare a global in main and then use
extern int lines;? But that doesn't seem to work. What am i doing wrong?
Should it be static?

Nov 13 '05 #1
6 9579

"atv" <al**@xs4all.nl > wrote in message news:3F******** ******@xs4all.n l...
Alright, i have some questions concerning include files en global
variables.I hope someone is willing to answer these.

1).Why is it that if i define a global variable in a file, say main.c,
and i have also other functions defined in that file, i can use the
global in all functions, but once i split up the rest of the function in
other files, i cannot use the global? Isn't that strange, all the files
compiled should be treated as one program right ?

Or should i always define the variables somewhere, say main.c, and use
extern char var[]; in the other source files?
If you have to use globals then the variable will be available to that file.
To use it in another .c file then yes you must use
extern TYPE VAR
The reason it is not immediately available to other files (I think) is to do
with scope. A global variable in one file has scope throughout the whole
file but not in others, just like if a variable is defined in a function -
it has scope within that function but not in others.

2). What is the proper way to use include files? If i split my code and
functions up in different files, what is the normal way of using
includes. Do you, each time for a new file, have a list of the includes
setup again in that file, or ?

Right now, i have a method i saw from some other code, by defining all
the include headers in one include.h, and using that include for all
files. That way you only have to include a file once, saves a lot of
typing. Is this a correct way or a very bad way of doing things.
What I do is use a "stdhdrs.h" which includes the common headers required
for my type of app. At the moment I am programming an OpenGL app in windows
so it looks like

#include <windows.h>
#include <fstream>
#include <gl\gl.h>
#include <gl\glu.h>
#include <cmath>

#pragma once // include only once

#define APP_VERSION "WinGalaga v0.0.3"

#define ENTER 13
#define ALTGR 17
#define SPACE ' '

(You may also notice that it uses c++ headers, but thats aside). As for
what should be in a .h file then I put in the function prototypes and not
much else, but the minimum to get it to compile. You should also have good
comments in your header file for usage.

3). I have code that is split up in multiple files. The main function
sits in main.c, and calls for example, a logging function, which sits
in log.c. Now log() needs to remember the amount of lines it has
written. How would i do this ? Declare a global in main and then use
extern int lines;? But that doesn't seem to work. What am i doing wrong?
Should it be static?


There are many ways to do this. Microsoft tend to throw everything into a
struct, I prefer to pass pointers e.g.

int log(int *xoNumLines)
{
// do something
*xoNumLines = NumLinesRead; // or whatever
}

HTH
Allan
Nov 13 '05 #2
j

"atv" <al**@xs4all.nl > wrote in message news:3F******** ******@xs4all.n l...
Alright, i have some questions concerning include files en global
variables.I hope someone is willing to answer these.

1).Why is it that if i define a global variable in a file, say main.c,
and i have also other functions defined in that file, i can use the
global in all functions, but once i split up the rest of the function in
other files, i cannot use the global? Isn't that strange, all the files
compiled should be treated as one program right ?

Because what you think ``global'' means, isn't really global. It is a
misleading term.
Each translation unit will need a local declaration of the file-scope
variable
that has external linkage.
Or should i always define the variables somewhere, say main.c, and use
extern char var[]; in the other source files?
The definition can exist in your main translation unit(depending on the
purpose of the variable)
and can be identified elsewhere with the use of ``extern'' and if it is an
array, then
``extern char var[]'' would work.

2). What is the proper way to use include files? If i split my code and
functions up in different files, what is the normal way of using
includes. Do you, each time for a new file, have a list of the includes
setup again in that file, or ?

Hm, well.. if you use a set of standard headers throughout several
translation units
then grouping those commonly used standard headers in a common header file
seems okay to me. Certainly beats the otherwise toilsome work if you have
to deal with several translation units.
Right now, i have a method i saw from some other code, by defining all
the include headers in one include.h, and using that include for all
files. That way you only have to include a file once, saves a lot of
typing. Is this a correct way or a very bad way of doing things.

3). I have code that is split up in multiple files. The main function
sits in main.c, and calls for example, a logging function, which sits
in log.c. Now log() needs to remember the amount of lines it has
written. How would i do this ? Declare a global in main and then use
extern int lines;? But that doesn't seem to work. What am i doing wrong?
Should it be static?


Well, if the variable's purpose is to be used in this function only, then a
variable with
static storage is sufficient. I think you also need to ask yourself, how
many lines
do you expect this logfile to build up to? An int certainly won't hold that
much.
Nov 13 '05 #3
On Wed, 05 Nov 2003 11:53:12 +0100, atv <al**@xs4all.nl > wrote:
Alright, i have some questions concerning include files en global
variables.I hope someone is willing to answer these.

1).Why is it that if i define a global variable in a file, say main.c,
and i have also other functions defined in that file, i can use the
global in all functions, but once i split up the rest of the function in
other files, i cannot use the global? Isn't that strange, all the files
compiled should be treated as one program right ?
It's all in visibility, really. A file scope variable with external linkage
defined in one translation unit will not just automagically be seen in other
translation units (because you do not compile a "program", you compile a
translation unit (which is, roughly, the processed *.c file after preprocessing
and various other stages).

To refer to a variable with external linkage defined somewhere (including, but
not limited to, the current translation unit), you would put

extern int i;

which tells the C compiler that `i' exists somewhere.

Or should i always define the variables somewhere, say main.c, and use
extern char var[]; in the other source files?
Yes, but you would normally put that line in the header file main.h and include
that header file.

2). What is the proper way to use include files? If i split my code and
functions up in different files, what is the normal way of using
includes. Do you, each time for a new file, have a list of the includes
setup again in that file, or ?
Yes, or wrap them in a single "includer", if that makes sense. But pay attention
so that no .h file is included more than once, because in most cases it is an
error (resulting in multiple definition errors). This can be achieved relatively
easily by using so called "inclusion guard". For example, to guard foo.h against
multiple inclusions, you would write something like

#ifndef FOO_H
#define FOO_H

/* body of foo.h here ... */

#endif
From now on, you don't have to worry that a file will be included more than once
in one translation unit. There are of course some other compiler-specific
solutions to prevent multiple inclusions (like #pragma once) which are a tiny
bit better (since you don't use up the preprocessor namespace), but these
pragmas are not portable, so better stick to the ifndef/endif trick.

Right now, i have a method i saw from some other code, by defining all
the include headers in one include.h, and using that include for all
files. That way you only have to include a file once, saves a lot of
typing. Is this a correct way or a very bad way of doing things.

It wouldn't do any harm, normally.
3). I have code that is split up in multiple files. The main function
sits in main.c, and calls for example, a logging function, which sits
in log.c. Now log() needs to remember the amount of lines it has
written. How would i do this ? Declare a global in main and then use
extern int lines;? But that doesn't seem to work. What am i doing wrong?
Should it be static?


The approach should work, if you're defining `int lines;' as a file scope
variable in main.c, and declaring it as `extern int lines;' either at file scope
in log.c, inside log(), or both.

Using a static variable inside log() another possible approach. It all depends
on what you want to do.
Nov 13 '05 #4
atv wrote:

Alright, i have some questions concerning include files en global
variables.I hope someone is willing to answer these.

1). Why is it that if i define a global variable in a file, say
main.c, and i have also other functions defined in that file, i
can use the global in all functions, but once i split up the rest
of the function in other files, i cannot use the global? Isn't
that strange, all the files compiled should be treated as one
program right ?
No.

Or should i always define the variables somewhere, say main.c,
and use extern char var[]; in the other source files?
Yes. You should define it where it has its primary use. With
good design you will often find it is not needed as a 'global'
anyhow. Global is a misnomer anyhow, and I assume you are using
it to define something that has static duration and external
scope.

2). What is the proper way to use include files? If i split my
code and functions up in different files, what is the normal
way of using includes. Do you, each time for a new file, have a
list of the includes setup again in that file, or ?
The include file is used to specify the access allowed to the code
file. I.e., if you have written foo.c, then foo.h specifies those
elements of foo.c visible in other files. In those other files
you make them visible by including foo.h. You also include foo.h
in foo.c to ensure that those definitions are consistent. Include
guards are also handy.

This is NOT mandated by the standards, compilers, etc. but is
simply good practice.

Right now, i have a method i saw from some other code, by
defining all the include headers in one include.h, and using
that include for all files. That way you only have to include
a file once, saves a lot of typing. Is this a correct way or
a very bad way of doing things.
Ugh. This is analogous to always leaving your car with the keys
in the ignition and engine running. Both tend to lead to total
loss of control.

3). I have code that is split up in multiple files. The main
function sits in main.c, and calls for example, a logging
function, which sits in log.c. Now log() needs to remember the
amount of lines it has written. How would i do this ? Declare
a global in main and then use extern int lines;? But that doesn't
seem to work. What am i doing wrong? Should it be static?


That depends on what needs to know that count of lines. If only
log(), declare it as local to the log() function. If it has to
preserve its value between calls, make it static. If doing that
fouls up re-entrancy, pass its location to log as a parameter.

BTW your use of i in place of the (upper case) pronoun I is
annoying.

--
Chuck F (cb********@yah oo.com) (cb********@wor ldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net> USE worldnet address!
Nov 13 '05 #5
"j" <ja**********@b ellsouth.net> wrote in message
news:A_******** **********@bign ews6.bellsouth. net...

"atv" <al**@xs4all.nl > wrote in message news:3F******** ******@xs4all.n l...
Alright, i have some questions concerning include files en global
variables.I hope someone is willing to answer these.

1).Why is it that if i define a global variable in a file, say main.c,
and i have also other functions defined in that file, i can use the
global in all functions, but once i split up the rest of the function in
other files, i cannot use the global? Isn't that strange, all the files
compiled should be treated as one program right ?


Because what you think ``global'' means, isn't really global. It is a
misleading term.

[snip]

Maybe that's why my copy of N869 doesn't mention 'global
variables', and instead defines 'scopes of identifiers' (6.2.1).
OK, OK, there is 1 (one) reference to term 'global variable'
(F.8.1-1). Without any definition of the term. It leads me to
believe that it was forgotten to be purged by mistake. But as
usual, I can be wrong.

[snip]
Nov 13 '05 #6
"CBFalconer " <cb********@yah oo.com> wrote in message
news:3F******** *******@yahoo.c om...
atv wrote:


2). What is the proper way to use include files? If i split my
code and functions up in different files, what is the normal
way of using includes. Do you, each time for a new file, have a
list of the includes setup again in that file, or ?


The include file is used to specify the access allowed to the code
file. I.e., if you have written foo.c, then foo.h specifies those
elements of foo.c visible in other files. In those other files
you make them visible by including foo.h. You also include foo.h
in foo.c to ensure that those definitions are consistent. Include
guards are also handy.

This is NOT mandated by the standards, compilers, etc. but is
simply good practice.

Right now, i have a method i saw from some other code, by
defining all the include headers in one include.h, and using
that include for all files. That way you only have to include
a file once, saves a lot of typing. Is this a correct way or
a very bad way of doing things.


Ugh. This is analogous to always leaving your car with the keys
in the ignition and engine running. Both tend to lead to total
loss of control.

<ot>
That is right. To regain control back may be *very* time consuming.
Suppose one is working on big project and has to use libraries
writen by other people (likely long gone from company). Library
authors "convenient ly" provided "header dump" header files - one
per library. All those "top-level" include other files and they
include other and so on with almost arbitrary level of nesting
(I guess there is some limit in standard, but even without
reaching limit it can be quite a mess). One day one discovers
(s)he needs to use e.g. two of those libraries in program.
However, somwhere deep inside, one is using macro identifier
where the other is using same identifier as enumeration constant.
All would be well if one could rearrange order of includes, but
one can't (one is dependent on the other). So one has to throw
away "global" include files, dissect them up to "leaves" of
"include tree" (from all used libraries), take only "leaf"
include files and include them in correct order in C source file.
After this kind of experience, *I* prefer to spend few seconds
more today (to type in or copy/paste include directives only
for stuff that I need), than hours or days later just to get
the damn thing to compile.
This is not to say that there doesn't exist recently arrived
"profession al" who would suggest to defer today's problem
avoidance to tomorrow's problem fixing, preferably at the
expense of someone else.
Here one gets only advice, choice is his/hers.
</ot>

[snip]
Nov 13 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
2030
by: exits funnel | last post by:
Hello, I have the following three files //BEGIN test.h class foo { public: void print( ); private:
111
6472
by: JKop | last post by:
Okay here we go, I feel it's about time people conversed about the bullshit aspects of C++ (including the bullshit stuff brought forward from C). I'll begin with a few of my own grievances: 1) The whole "function declaration Vs object definition" fiasco, which results in the following (temporary creating) syntax: Blah poo = Blah();
2
3486
by: flyaflya | last post by:
I want use a c lib in vc6. so I use extern "C" to c function, include three files "test.cpp", "b.h" and "b.c": //************************************************ // test.cpp #include "stdafx.h" #include "b.h" int main(int argc, char* argv) {
1
2029
by: smackdab | last post by:
Hi, I am using MSVC to compile GD and I think I am down to my last problem (we'll see ;-) I can compile libgd.dll and libgd.lib ok but a gdtest.exe program that refers to extern font variables are not defined and I have no idea how this should work...sorry for the confusing email, the more I write, the worse it becomes ;-) SHORT VERSION>
7
9041
by: Kieran Simkin | last post by:
I have in my project in main.c a number of arrays defined like this (outside of any functions): char muser, mpass; I'm declaring them in a number of other .c files (inside functions) like this: extern char muser, mpass; However, in one of these functions outside of main.c I need to snprintf into these buffers. Usually when using snprintf I call it like this: snprintf(muser, sizeof muser, "text");
2
1351
by: yogeshmk | last post by:
I've a problem with array values getting lost in function call. Here is the flow. ===========driver.c================= /* this is just a driver to test a library wrapper * originally it's a cobol program calling a c library function */ # include "il_entry.h" /* # define s SCANFUN as il_lib_entry */
5
1937
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.
5
3609
by: Rahul | last post by:
Hi Everyone, I wanted to know if the following declaration is valid? extern int i = 10; #include <cstdio> int main() {
21
2763
by: Christian Meier | last post by:
Hello NG I have the following code: file1.h: static const int iValue = 5; <EOF>
0
9453
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,...
0
10254
Oralloy
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...
0
10099
jinu1996
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...
1
7451
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6710
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5354
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...
0
5481
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4007
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2849
bsmnconsultancy
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...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.