I am studying header files in C right now. If I am to understandcorrectly, heade
ID: 3610108 • Letter: I
Question
I am studying header files in C right now. If I am to understandcorrectly, header files can only house functions? There is no wayto hold global variables? I can't seem to find a header file thathas global variables and declaring a variable in a header fileseems to screw up compiling it with it's respective C file.If I am incorrect please provide a basic header with it'srespective C file which will prove me wrong. Doesn't have to befancy, just one basic variable in a header, and the main to call itand display it.
Explanation / Answer
Generally speaking, if a global variable is going to be usedin more than 2 files, it’s better to use the header fileapproach. Some programmers place all of a programs global variablesin a file called globals.cpp, and create a header file namedglobals.h to be included by other .cpp files that need to usethem.Here is an example of using a header file extern: global.cpp: // declaration of g_nValue
- int g_nValue = 5;
- #ifndef GLOBAL_H // header guards
- #define GLOBAL_H
- // extern tells the compiler this variable is declared elsewhere
- extern int g_nValue;
- #endif
- #include "global.h"
- int main()
- {
- g_nValue = 7;
- return 0;
- }
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.