Jump to content
  • Advertisement
Sign in to follow this  
Token

global vars in C (simple question)

This topic is 4424 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!