Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

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  
  1. int g_nValue = 5;  
int g_nValue = 5;   // declaration of g_nValueint g_nValue = 5; global.h:
  1. #ifndef GLOBAL_H // header guards  
  2. #define GLOBAL_H   
  3.   
  4. // extern tells the compiler this variable is declared elsewhere  
  5. extern int g_nValue;   
  6.   
  7. #endif  
#ifndef GLOBAL_H // header guards   #define GLOBAL_H       // extern tells the compiler this variable is declared elsewhere   extern int g_nValue;       #endif   #ifndef GLOBAL_H // headerguards #define GLOBAL_H// extern tells the compiler this variableis declared elsewhere extern int g_nValue;#endif main.cpp:
  1. #include "global.h"   
  2. int main()   
  3. {   
  4.     g_nValue = 7;  
  5.     return 0;   
  6. }  
#include "global.h"    int main()    {        g_nValue = 7;       return 0;    }  
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote