C++
inline function defined in source file? or header file?
GunwooYun
2024. 1. 20. 20:12
나의 센서 챗지피티 형님께 여쭤봤다.
형의 대답은 다음과 같다.
- Visibility and Inlining Across Translation Units:
- When an inline function is defined in a header file, its definition is available to multiple translation units (source files). This allows the compiler to potentially inline the function in each translation unit where it is used.
- Placing the definition in a source file might limit the compiler's ability to inline the function across multiple source files.
- One Definition Rule (ODR):
- If an inline function is defined in multiple translation units, the definitions must be identical. Placing the definition in a header file helps ensure consistency across different source files.
- Ease of Use:
- Including the header file with the inline function definition allows users of your code to benefit from inlining without having to manually duplicate the function definition in each source file.
해석하자면,
1. 번역단위의 가시성과 인라이닝
* 헤더파일에 정의해 놓으면, 여러 소스파일에서 번역하여 사용 가능해진다. 이건 컴파일러가 각 번역마다 함수를 인라인할 수 있게 해준다.
* 함수 정의를 소스파일에 해놓으면 컴파일러가 여러 소스파일에 인라인을 할 수 있는 것이 제한적이된다.
-> 거의 비슷한 말인 듯 하다. 헤더파일에 해 놓으면 해당 헤더파일을 include 하는 소스파일들은 정의된 인라인을 사용할 수 있게 되지만, 소스파일에만 정의되어 있을 경우, 해당 소스파일에만 적용이 가능하다.
2. 1회 정의 룰
* 중복되어 정의되어서는 안된다.
3. 쉬운 사용
* 여러 소스파일에서 정의하지 않아도 된다. 곧 헤더파일에 정의해놓으면 귀찮게시리 사용하는 소스파일마다 정의하지 않아도 된다는 뜻.
역시 센세.