궁금한게 많은 개발자 노트

[ C/C++ ] include header 작성법 본문

Language

[ C/C++ ] include header 작성법

궁금한게 많은 개발자 2020. 12. 9. 10:20

개발을 하다보면 많은 라이브러리들을 참조하게 되고, 그 라이브러리에서 제공하는 header file을 include하게 된다.
또한 그것들을 응요하여 각 프로젝트에 맞는 header file을 작성하게 되면서 수 많은 head file들을 cpp에서 include하여 그에 맞는 기능들을 구현하여야 한다.

그러한 header file들을 이제까지는 알파벳순 또는 대충 비슷한 기능을 가지고 있는 것들끼리 묶어서 선언하곤 했다.
조금 보기에 그럴싸해 보기에 작성했던 것 같다. 그러던 도중 선배님이 리뷰를 달아주셔서 찾아보니..

 

Google C++ Style Guide

Google C++ Style Guide Background C++ is one of the main development languages used by many of Google's open-source projects. As every C++ programmer knows, the language has many powerful features, but this power brings with it complexity, which in turn ca

google.github.io

구글에서 권장하는 법칙같은게 있었다. 되도록이면 많은 사람과 함께 일을 할때는 저러한 가이드를 따라 개발하는 습관을 들이면 좋다. 엄청 똑똑하신 분들이 정해놓은 법칙이라 무조건 따라하는게 좋을거 같다 :)

 

Names and Order of Includes

Include headers in the following order: Related header, C system headers, C++ standard library headers, other libraries' headers, your project's headers.

All of a project's header files should be listed as descendants of the project's source directory without use of UNIX directory aliases . (the current directory) or .. (the parent directory). For example, google-awesome-project/src/base/logging.h should be included as:

#include "base/logging.h"

In dir/foo.cc or dir/foo_test.cc, whose main purpose is to implement or test the stuff in dir2/foo2.h, order your includes as follows:

    1. dir2/foo2.h.
    2. A blank line
    3. C system headers (more precisely: headers in angle brackets with the .h extension), e.g., <unistd.h>, <stdlib.h>.
    4. A blank line
    5. C++ standard library headers (without file extension), e.g., <algorithm>, <cstddef>.
    6. A blank line
    7. Other libraries' .h files
    8. Your project's .h files

 

Separate each non-empty group with one blank line.

 

대충 해석을 해보면 c++에서는 hpp파일이 있고 그곳에 선언된 기능들을 구현하는 cpp파일이 있을텐데,
cpp파일에서 include하는 순서는 해당 cpp와 매칭되는 hpp(예를 들면 foo.hpp와 foo.cpp)를 가장 위에 선언하고 빈줄
그 이후 C system headers(꺽쇠로 둘러싸여 있는 stdio.h, stdlib.h와 같은)를 쓰고 빈줄이 오고
C++ standard library headers(파일 확장자가 없는 iostream, algorithm과 같은)을 쓰고 빈줄이 오고
그 다음은 다른 라이브러리에서 가져온 header file들을 선언해주고 그 이후는 내 프로젝트에서 생성한 헤더파일을 순서대로 써주면 된다. 실제로 복잡해 보이지만 아래 예시에서 보이는것 처럼 깔끔하게 정리가 된다.

예를 들어 google-awesome-project/src/foo/internal/fooserver.cpp의 경우에는 다음과 같은 순서로 선언할 수 있다.

#include "foo/server/fooserver.h"

#include <sys/types.h>
#include <unistd.h>

#include <string>
#include <vector>

#include "base/basictypes.h"
#include "base/commandlineflags.h"
#include "foo/server/bar.h"

 

현재 작업하고 있는 프로젝트는 어떤 순서로 되어있는지 보고, 참고해보면 좋을것 같다 :)

Comments