Search code examples
c++includestdio

#include stdio confusion is it needed for each header file?


I know my understanding of #include or how it is compiled is not correct otherwise the code I have would work. I'm confused on why my code needs #include in two locations in order to compile and run correctly.

My main cpp file armperfmon.cpp:

#include "armperfmon.h"
int main(int argc, char* argv[])
{
    FILE* pOutFile = NULL;
    PrintCounterOptions(pOutFile);
}

main header file armperfmon.h:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "counters.h"

void PrintCounterOptions(FILE* pFile);

second cpp containing function counters.cpp:

void PrintCounterOptions(FILE* pFile)
{
    fprintf("print some stuff");
}

second header file for function counters.h

void PrintCounterOptions(FILE* pFile);

The error:

counters.cpp: error: 'FILE' was not declared in this scope
counters.cpp: error: 'pFile' was not declared in this scope

if I enter #include <stdio.h> in the function cpp file then the error goes away and the function compiles/executes as expected. I assumed that in the main.h file when it included <stdio.h> it would be available for use for subsequent FILE* definitions especially because it is included before counters.h is included. As I type this I'm also realizing the more correct include is <cstdio>. If someone could clarify what is wrong with my thought process it would be much appreciated.


Solution

  • It's hard to answer this exactly because you've stripped out all the specific details like filenames but, in brief, C++ source files are compiled independently before the results are linked together, and the "main header" is not seen at all while compiling the "second cpp": it's only the header for your "main cpp file". Indeed, the entire purpose of header files is to serve as a common location for declarations that shall then be #included into multiple translation units, which is what you need to do here by adding the necessary code to your "second header file".