Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between putting variables in header vs putting variables in source

Tags:

c

extern

header

Say I declare a header file with a variable:

int count;

Then in the source file, I want to use count. Do I have to declare it as:

extern int count

Or can I just use it in my source file? All assuming that I have #include "someheader.h". Or should I just declare it in the source file? What is the difference between putting count in the header file vs the source file? Or does it not matter?

like image 657
Mohit Deshpande Avatar asked Sep 19 '25 07:09

Mohit Deshpande


2 Answers

You only want one count variable, right? Well this line:

int count;

Defines a count variable for you. If you stick that in multiple files (by including it in a header), then you'll have multiple count variables, one for each file, and you'll get errors because they'll all have the same name.

All the extern keyword does is say that there is a count variable defined in some other file, and we're just letting the compiler know about it so we can use it in this file. So the extern declaration is what you want to put in your header to be included by your other files. Put the int count; definition in one source file.

like image 65
Paige Ruten Avatar answered Sep 21 '25 23:09

Paige Ruten


If you did put that into the header, then yes, you could just use it in the source file without any further declaration (after the point where the header has been #included, anyway).

#include "someheader.h" effectively just copies the contents of someheader.h in, as if it had all been directly written in the including file at that point.

However, this is not the way you're supposed to use headers. int count; is a tentative definition - you are supposed to only put declarations in header files. So someheader.h should have:

extern int count;

(which is just a declaration), and exactly one source file in your application should define count:

int count = 0;

The others can just #include "someheader.h" and use count.

like image 37
caf Avatar answered Sep 21 '25 23:09

caf