/ The Blog of Jinho Ko / Computer science / Programming / C++

·

1 min read

HPP vs CPP : Conventions

By Jinho Ko

How compilation in C++ works

Conventions of where to write code in

  • 일반적인 convention은, declaration은 hpp에, definition은 cpp에 하는 것이 정석임 (OOP 101 level)
  • 그러나, 예외적으로 고려해봐야 할 2가지 케이스가 있음:
    • template
    • inline;

Why can templates only be implemented in header file?

https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file

The compiler needs to instantiate the template in the compilation step. Thus the compiler needs to have access to the implementation of the methods. If these implementations were not in the header, they wouldn’t be accessible, and therefore the compiler wouldn’t be able to instantiate the template.

Alternative solution : explicit template instantiation

Inlining

Overview:

(+) Decrease cost of function call

  • New stack frame setup
  • Return-value communication
  • Restoring the old stack frame

(-) Code size increase

‘inline’ keyword in C++

https://docs.microsoft.com/ko-kr/cpp/cpp/inline-functions-cpp?view=msvc-160

To be precise,이게 inline을 해라 라는 뜻은 아님. Compiler의 선택에 따라 inline 선언한 것도 안할 수도 있음.

Since the definition of the function should be known in order to inline functions, it is general to define both declaration and definition in the header. (linking-time inlining이 가능하기는 한데, 까다롭고 opt면에서 추천하지 않는다고 함)

https://www.ibm.com/docs/en/xl-c-and-cpp-aix/13.1.2?topic=specifiers-inline-function-specifier

https://othereum.github.io/c/c++/inline/

Why avoid implementation in hpp

https://blog.knatten.org/2012/11/09/another-reason-to-avoid-includes-in-headers/

  • header에 구현을 하게 되면, 그 header의 수정이 발생할 때 dependency가 있는 모든 file들이 recompile됨. Compilation time이 증가함.
  • 이를 막기 위한 테크닉으로 포인터 객체에 대해서는 forward declaration을 사용해 컴파일 타임을 빠르게 가져갈 수 있음.

References

last modified June 2, 2024
comments powered by Disqus

© Copyright 2024. Jinho Ko. All rights reserved. Last updated: June 02, 2024.