#包含stdio混淆是每个头文件所需要的

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

本文关键字:文件 stdio 包含      更新时间:2023-10-16

我知道我对#include的理解或它的编译方式是不正确的,否则我的代码就会工作。我很困惑为什么我的代码需要在两个位置包含#include才能正确编译和运行。

我的主cpp文件armperfmon.cpp:

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

主头文件armperfmon.h:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "counters.h"
void PrintCounterOptions(FILE* pFile);

第二个包含函数counter.cpp:的cpp

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

函数计数器的第二个头文件.h

void PrintCounterOptions(FILE* pFile);

错误:

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

如果我在函数cpp文件中输入#include <stdio.h>,那么错误就会消失,函数会按预期编译/执行。我假设在主.h文件中,当它包含<stdio.h>时,它将可用于后续的file*定义,特别是因为它包含在counters.h之前。当我输入这个时,我也意识到更正确的include是<cstdio>。如果有人能澄清我的思维过程中出了什么问题,我将不胜感激。

很难准确回答这个问题,因为你已经去掉了所有特定的细节,比如文件名,但简而言之,C++源文件在结果链接在一起之前是独立编译的,在编译"第二个cpp"时根本看不到"主头":它只是"主cpp文件"的头。实际上,头文件的全部目的是作为声明的公共位置,然后将声明#included转换为多个转换单元,这就是您需要在这里通过向"第二个头文件"添加必要的代码来实现的。