簡體   English   中英

#include stdio混淆是否需要每個頭文件?

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

我知道我對#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);

第二個包含功能counters.cpp的cpp:

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

功能counters.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> ,則錯誤消失並且該函數按預期編譯/執行。 我假設在main.h文件中,當它包含<stdio.h> ,它將可用於后續的FILE *定義,尤其是因為它是在包含counters.h之前包含在內的。 鍵入此命令時,我還意識到更正確的include是<cstdio> 如果有人可以澄清我的思考過程出了什么問題,將不勝感激。

很難完全回答這個問題,因為您已經去除了文件名之類的所有特定詳細信息,但總之,C ++源文件在結果鏈接在一起之前是獨立編譯的,而在編譯C ++源文件時根本看不到“主標頭” “第二個cpp”:僅是“主cpp文件”的標題。 實際上,頭文件的全部目的是用作聲明的公共位置,然后將聲明#include到多個轉換單元中,這是您需要在此處通過將必要的代碼添加到“第二個頭文件”中來進行的操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM