Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
585 views
in Technique[技术] by (71.8m points)

c - Difference between putting variables in header vs putting variables in source

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...