![](/img/trans.png)
[英]How do I know which C++ source files include a specific h header file
[英]How do I prevent a source file from depending on an include inside a header file?
//Foo.h
#include <string>
struct Foo;
//main.cpp
#include "Foo.h"
int main(int argc, char *argv[])
{
std::string s = "hello";
}
我在這段代碼中#include <string>
的問題是#include <string>
泄漏到main.cpp中。 main.cpp中需要#include <string>
進行編譯,但是如果在將來的版本中Foo.h
不再需要字符串,則main.cpp將不會編譯。
有辦法防止這種情況嗎?
編輯:我知道我可以通過始終包含我需要的每個文件來自己進行管理,但是我在一個團隊中工作,每個人都做自己的事,這完全是一團糟。 所以我想知道是否有一種方法可以強制執行此操作。
評論似乎表明我們必須手動進行管理。 我想這回答了我的問題。
不,沒有自動的方法來保護自己,以防止自己無意中依賴通過其他標頭包含的標頭。
您需要做的就是規管自己,使其在使用它們的每個源文件中包括相關的頭,即使每個源文件中並非嚴格要求每個#include
指令也是如此。
不過,忘記的后果並不可怕。 如果Foo.h最終更改為不再包含string ,則代碼將無法編譯,但是修復很容易,幾乎不需要時間。 不用擔心。
讓每個文件僅包含其真正需要的依賴項。 另外,您還應該使用包含保護( C ++ #include guards )保護自己的頭文件。
foo.h中:
#ifndef _INCLUDED_FOO_H_
#define _INCLUDED_FOO_H_
// Only #include <string> here if it is needed in the Foo.h
// ...
struct Foo;
// ...
#endif
main.cpp中:
#include <string>
#include "Foo.h"
int main(int argc, char *argv[])
{
std::string s = "hello";
}
即使Foo.h隨后更改,main.cpp仍然可以編譯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.