Sign in to follow this  
Token

global vars in C (simple question)

Recommended Posts

Hi everyone! Every time I split my C source code in parts I have a problem with global variables declarations :) Let's assume I have one big source code file in my program. Then I split it into 3 parts: main.c //includes main() function file1.h //includes functions' prototypes file1.c //includes functions' bodies file2.h //includes other functions' prototypes file2.c //includes other functions' bodies Every function uses the same global variables: int i=5; char k='a'; How and where should I declare them to make it work as it was one big source file?

Share this post


Link to post
Share on other sites
You would typically declare them as external variables.

file1.h:
extern int MyVar; // Tell the compiler that this exist somewhere else...

file1.c:
int MyVar; // Exist in file1...

If you need this variable in file2.c for example, you include file1.h somewhere in file2.c:

#include "file1.h"

Share this post


Link to post
Share on other sites
You would put the gloabal variables in any .c file and declare them in other .c files that need them using: extern int i; extern char k; The reason (as you will find out by reading the link provided to you already) is because the extern keyword tells the compiler - at compile time - that the variables are somewhere else in the source files, and this will prevent the compiler from complaining. This is done at compile time. At link time, the linker will associate/link the extern variable declarations with their definitions that were defined in the .c file.

A declaration just tells the compiler something by this *name* exist somwehere else. A definition is *the* object, with storage set aside for it's specific data type size. Removing extern from an intended declaration variable will create a definition, and thus, at link time, the compiler will find two peices of storage with the same name and it will become a linker error. extern solves this problem because it does not create storage, but merely refers to an object that is defined in another file.

The second to last page of the "Organizing Code Files" article explains this in more detail so make sure to read over it carefully.

- xeddiex

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this