應儘可能地寫入標頭1)獨立於可能已包含的內容,2)不爲後面包含的標頭引入問題(例如常見標識符的宏)。當這兩個都是真實的時候,你包括的順序並不重要。如果這些不是真的,你應該在你自己的頭文件中解決這個問題,否則必要時處理它。
因此,選擇是任意的,但是您做出選擇仍然很重要! 「計劃沒有什麼,但計劃就是一切。」一致性導致更易讀的代碼。
相對常見的順序是標準庫,系統(如OS),外部庫,然後是與當前文件相同的項目的頭文件 - 除了包含其「對應」頭文件的實現文件之外(如果有一個)首先,在任何包含或其他代碼之前。在每個組中,我按照習慣按字母順序排序,因爲再一次,它完全是任意的,但是一些易於使用的順序讓我可以快速讀取和更新列表。
應用到你的列表:
// first only because this is required in your precompiled header setup
#include "stdafx.h"
// it's too bad this can't really be first
// I'm guessing "This" refers to the corresponding header
#include "This.h"
// C stdlib then C++ stdlib is what I usually do,
// whether the C headers are spelled XXX.h or cXXX.
#include <math.h>
#include <stdio.h>
#include <iostream>
#include <list>
#include <string>
// someone mentioned winsock2 needs to be before windows
#include <Winsock2.h>
#include <tchar.h>
#include <Windows.h>
#include <boost/regex.hpp>
#include "mystring_written_by_c.h"
#include "mystring_written_by_cpp.h"
換行符上面分成組是故意的。我會留下評論,爲什麼winsock2有自己的組,但其餘的評論通常不會在那裏。
您是否有錯誤,或者您在詢問訂購`#include`指令的最佳做法是什麼? – 2011-01-26 02:47:01
最佳實踐。 – Benjamin 2011-01-26 02:49:07
可能的重複:http://stackoverflow.com/questions/614302/c-header-order。另外:http://stackoverflow.com/questions/2762568/c-c-include-file-order-best-practices。 – Maxpm 2011-01-26 02:52:36