문제

나는 항상 사용했습니다 *.h 내 수업 정의에 대한 파일이지만 부스트 라이브러리 코드를 읽은 후에는 모두 그들이 사용한다는 것을 깨달았습니다. *.hpp. 나는 항상 그 파일 확장에 대한 혐오감을 가지고 있었는데, 나는 주로 익숙하지 않기 때문에 생각합니다.

사용의 장점과 단점은 무엇입니까? *.hpp ~ 위에 *.h?

도움이 되었습니까?

해결책

다음은 C 대 C ++ 헤더의 다른 명명을 갖는 몇 가지 이유입니다.

  • 자동 코드 형식에는 C 및 C ++ 코드 포맷에 대한 지침이 다를 수 있습니다. 헤더가 확장자별로 분리되면 편집기가 적절한 형식을 자동으로 적용하도록 설정할 수 있습니다.
  • 이름 지정, 저는 C로 작성된 라이브러리가있는 프로젝트를 수행 한 다음 C ++로 래퍼가 구현되었습니다. 헤더는 일반적으로 비슷한 이름, 즉 feature.h vs feature.hpp를 가지고 있으므로 분리하기 쉽습니다.
  • 포함, 프로젝트에는 C ++로 작성된 더 적절한 버전이 있지만 C 버전을 사용하고 있습니다 (위의 포인트 참조). 헤더가 구현 된 언어의 이름을 따서 명명 된 경우 모든 C 헤더를 쉽게 발견하고 C ++ 버전을 확인할 수 있습니다.

C를 기억하십시오 ~ 아니다 C ++ 및 자신이 무엇을하고 있는지 알지 못한다면 믹스 앤 일치하는 것은 매우 위험 할 수 있습니다. 출처의 이름을 적절하게 이름을 지정하면 언어를 구별하는 데 도움이됩니다.

다른 팁

사용자가 C ++ 헤더의 헤더와 C 헤더의 헤더가 무엇인지 구별하기를 원하기 때문에 .hpp를 사용합니다.

프로젝트가 C와 C ++ 모듈을 모두 사용하는 경우 중요 할 수 있습니다. 다른 사람이 저 앞에 설명한 것처럼, 당신은 매우 신중하게 수행해야하며, 연장을 통해 제공하는 "계약"으로 시작해야합니다.

.hpp : C ++ 헤더

(또는 .hxx, 또는 .hh 또는 무엇이든)

이 헤더는 C ++ 전용입니다.

C 모듈에 있다면 포함시키지 마십시오. C 친화적으로 만들기 위해 노력하지 않기 때문에 마음에 들지 않을 것입니다 (기능 과부하, 네임 스페이스 등과 같이 너무 많이 손실 될 것입니다).

.h : C/C ++ 호환 또는 순수한 C 헤더

이 헤더는 C 소스와 C ++ 소스 모두 직간접 적으로 포함 할 수 있습니다.

직접적으로 포함될 수 있으며 __cplusplus 매크로 :

  • 이는 C ++ 관점에서 C 호환 코드가 다음과 같이 정의됩니다. extern "C".
  • C 관점에서 모든 C 코드는 명확하게 표시되지만 C ++ 코드는 숨겨집니다 (C 컴파일러에서 컴파일하지 않기 때문에).

예를 들어:

#ifndef MY_HEADER_H
#define MY_HEADER_H

   #ifdef __cplusplus
      extern "C"
      {
   #endif

   void myCFunction() ;

   #ifdef __cplusplus
      } // extern "C"
   #endif

#endif // MY_HEADER_H

또는 해당 .hpp 헤더에 의해 간접적으로 포함될 수 있습니다. extern "C" 선언.

예를 들어:

#ifndef MY_HEADER_HPP
#define MY_HEADER_HPP

extern "C"
{
#include "my_header.h"
}

#endif // MY_HEADER_HPP

그리고:

#ifndef MY_HEADER_H
#define MY_HEADER_H

void myCFunction() ;

#endif // MY_HEADER_H

나는 항상 고려했다 .hpp 일종의 포트만 토가 될 헤더 .h 그리고 .cpp 파일 ... 구현 세부 정보도 포함 된 헤더.

일반적으로 내가 보았을 때 (그리고 사용) .hpp 연장으로서 해당하는 것은 없습니다 .cpp 파일. 다른 사람들이 말했듯이, 이것은 어렵고 빠른 규칙이 아니며, 내가 어떻게 사용하는지 .hpp 파일.

어떤 확장을 사용하는지는 중요하지 않습니다. 어느 쪽이든 괜찮습니다.

나는 사용한다 *.h C와 *.hpp C ++의 경우.

EDIT [Added suggestion from Dan Nissenbaum]:

By one convention, .hpp files are used when the prototypes are defined in the header itself. Such definitions in headers are useful in case of templates, since the compiler generates the code for each type only on template instantiation. Hence, if they are not defined in header files, their definitions will not be resolved at link time from other compilation units. If your project is a C++ only project that makes heavy use of templates, this convention might be useful.

Certain template libraries that adhere to this convention provide headers with .hpp extensions to indicate that they do not have corresponding .cpp files.

Some other template libraries use another convention, like using .h for C headers and .hpp for C++; a good example would be the boost library.

Quote from Boost FAQ,

File extensions communicate the "type" of the file, both to humans and to computer programs. The '.h' extension is used for C header files, and therefore communicates the wrong thing about C++ header files. Using no extension communicates nothing and forces inspection of file contents to determine type. Using '.hpp' unambiguously identifies it as C++ header file, and works well in actual practice. (Rainer Deyke)

I've recently started using *.hpp for c++ headers.

The reason is that I use emacs as my primary editor and it enters automatically into c-mode when you load a *.h file and into c++-mode when you load a *.hpp file.

Apart that fact I see no good reasons for choosing *.h over *.hpp or vice-versa.

I'm answering this as an reminder, to give point to my comment(s) on "user1949346" answer to this same OP.


So as many already answered: either way is fine. Followed by emphasizes of their own impressions.

Introductory, as also in the previous named comments stated, my opinion is C++ header extensions are proposed to be .h if there is actually no reason against it.

Since the ISO/IEC documents use this notation of header files and no string matching to .hpp even occurs in their language documentations about C++.

But I'm now aiming for an approvable reason WHY either way is ok, and especially why it's not subject of the language it self.

So here we go.

The C++ documentation (I'm actually taking reference from the version N3690) defines that a header has to conform to the following syntax:

2.9 Header names

header-name:
    < h-char-sequence >
    " q-char-sequence "
h-char-sequence:
    h-char
    h-char-sequence h-char
h-char:
    any member of the source character set except new-line and >
q-char-sequence:
    q-char
    q-char-sequence q-char
q-char:
    any member of the source character set except new-line and "

So as we can extract from this part, the header file name may be anything that is valid in the source code, too. Except containing '\n' characters and depending on if it is to be included by <> it is not allowed to contain a >. Or the other way if it is included by ""-include it is not allowed to contain a ".

In other words: if you had a environment supporting filenames like prettyStupidIdea.>, an include like:

#include "prettyStupidIdea.>"

would be valid, but:

#include <prettyStupidIdea.>>

would be invalid. The other way around the same.

And even

#include <<.<>

would be a valid includable header file name.

Even this would conform to C++, it would be a pretty pretty stupid idea, tho.

And that's why .hpp is valid, too.

But it's not an outcome of the committees designing decisions for the language!

So discussing about to use .hpp is same as doing it about .cc, .mm or what ever else I read in other posts on this topic.

I have to admit I have no clue where .hpp came from1, but I would bet an inventor of some parsing tool, IDE or something else concerned with C++ came to this idea to optimize some internal processes or just to invent some (probably even for them necessarily) new naming conventions.

But it is not part of the language.

And whenever one decides to use it this way. May it be because he likes it most or because some applications of the workflow require it, it never2 is a requirement of the language. So whoever says "the pp is because it is used with C++", simply is wrong in regards of the languages definition.

C++ allows anything respecting the previous paragraph. And if there is anything the committee proposed to use, then it is using .h since this is the extension sued in all examples of the ISO document.

Conclusion:

As long you don't see/feel any need of using .h over .hpp or vise versa, you shouldn't bother. Because both would be form a valid header name of same quality in respect to the standard. And therefore anything that REQUIRES you to use .h or .hpp is an additional restriction of the standard which could even be contradicting with other additional restrictions not conform with each other. But as OP doesn't mention any additional language restriction, this is the only correct and approvable answer to the question

"*.h or *.hpp for your class definitions" is:

Both are equally correct and applicable as long as no external restrictions are present.


1From what I know, apparently, it is the boost framework that came up with that .hpp extension.

2Of course I can't say what some future versions will bring with it!

I prefer .hpp for C++ to make it clear to both editors and to other programmers that it is a C++ header rather than a C header file.

C++ ("C Plus Plus") makes sense as .cpp

Having header files with a .hpp extension doesn't have the same logical flow.

You can call your includes whatever you like.

Just need to specify that full name in the #include.

I suggest that if you work with C to use .h and when with C++ to use .hpp.

It is in the end just a convention.

Codegear C++Builder uses .hpp for header files automagically generated from Delphi source files, and .h files for your "own" header files.

So, when I'm writing a C++ header file I always use .h.

In one of my jobs in the early 90's, we used .cc and .hh for source and header files respectively. I still prefer it over all the alternatives, probably because it's easiest to type.

Bjarne Stroustrup and Herb Sutter have a statement to this question in their C++ Core guidelines found on: https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#S-source which is also refering to the latest changes in the standard extension (C++11, C++14, etc.)

SF.1: Use a .cpp suffix for code files and .h for interface files if your Y project doesn't already follow another convention Reason

It's a longstanding convention. But consistency is more important, so if your project uses something else, follow that. Note

This convention reflects a common use pattern: Headers are more often shared with C to compile as both C++ and C, which typically uses .h, and it's easier to name all headers .h instead of having different extensions for just those headers that are intended to be shared with C. On the other hand, implementation files are rarely shared with C and so should typically be distinguished from .c files, so it's normally best to name all C++ implementation files something else (such as .cpp).

The specific names .h and .cpp are not required (just recommended as a default) and other names are in widespread use. Examples are .hh, .C, and .cxx. Use such names equivalently. In this document, we refer to .h and .cpp > as a shorthand for header and implementation files, even though the actual extension may be different.

Your IDE (if you use one) may have strong opinions about suffices.

I'm not a big fan of this convention because if you are using a popular library like boost, your consistency is already broken and you should better use .hpp.

As many here have already mentioned, I also prefer using .hpp for header-only libraries that use template classes/functions. I prefer to use .h for header files accompanied by .cpp source files or shared or static libraries.

Most of the libraries I develop are template based and thus need to be header only, but when writing applications I tend to separate declaration from implementation and end up with .h and .cpp files

Fortunately, it is simple.

You should use the .hpp extension if you're working with C++ and you should use .h for C or mixing C and C++.

I use .h because that's what Microsoft uses, and what their code generator creates. No need to go against the grain.

In "The C++ Programming Language, Third Edition by Bjarne Stroustrup", the nº1 must-read C++ book, he uses *.h. So I assume the best practice is to use *.h.

However, *.hpp is fine as well!

It is easy for tools and humans to differentiate something. That's it.

In conventional use (by boost, etc), .hpp is specifically C++ headers. On the other hand, .h is for non-C++-only headers (mainly C). To precisely detect the language of the content is generally hard since there are many non-trivial cases, so this difference often makes a ready-to-use tool easy to write. For humans, once get the convention, it is also easy to remember and easy to use.

However, I'd point out the convention itself does not always work, as expected.

  • It is not forced by the specification of languages, neither C nor C++. There exist many projects which do not follow the convention. Once you need to merge (to mix) them, it can be troublesome.
  • .hpp itself is not the only choice. Why not .hh or .hxx? (Though anyway, you usually need at least one conventional rule about filenames and paths.)

I personally use both .h and .hpp in my C++ projects. I don't follow the convention above because:

  • The languages used by each part of the projects are explicitly documented. No chance to mix C and C++ in same module (directory). Every 3rdparty library is required to conforming to this rule.
  • The conformed language specifications and allowed language dialects used by the projects are also documented. (In fact, I even document the source of the standard features and bug fix (on the language standard) being used.) This is somewhat more important than distinguishing the used languages since it is too error-prone and the cost of test (e.g. compiler compatibility) may be significant (complicated and time-consuming), especially in a project which is already in almost pure C++. Filenames are too weak to handle this.
  • Even for the same C++ dialect, there may be more important properties suitable to the difference. For example, see the convention below.
  • Filenames are essentially pieces of fragile metadata. The violation of convention is not so easy to detect. To be stable dealing the content, a tool should eventually not only depend on names. The difference between extensions is only a hint. Tools using it should also not be expected behave same all the time, e.g. language-detecting of .h files on github.com. (There may be something in comments like shebang for these source files to be better metadata, but it is even not conventional like filenames, so also not reliable in general.)

I usually use .hpp on C++ headers and the headers should be used (maintained) in a header-only manner, e.g. as template libraries. For other headers in .h, either there is a corresponding .cpp file as implementation, or it is a non-C++ header. The latter is trivial to differentiate through the contents of the header by humans (or by tools with explicit embedded metadata, if needed).

The extension of the source file may have meaning to your build system, for example, you might have a rule in your makefile for .cpp or .c files, or your compiler (e.g. Microsoft cl.exe) might compile the file as C or C++ depending on the extension.

Because you have to provide the whole filename to the #include directive, the header file extension is irrelevant. You can include a .c file in another source file if you like, because it's just a textual include. Your compiler might have an option to dump the preprocessed output which will make this clear (Microsoft: /P to preprocess to file, /E to preprocess to stdout, /EP to omit #line directives, /C to retain comments)

You might choose to use .hpp for files that are only relevant to the C++ environment, i.e. they use features that won't compile in C.

There is no advantage to any particular extension, other than that one may have a different meaning to you, the compiler, and/or your tools. header.h is a valid header. header.hpp is a valid header. header.hh is a valid header. header.hx is a valid header. h.header is a valid header. this.is.not.a.valid.header is a valid header in denial. ihjkflajfajfklaf is a valid header. As long as the name can be parsed properly by the compiler, and the file system supports it, it's a valid header, and the only advantage to its extension is what one reads into it.

That being said, being able to accurately make assumptions based on the extension is very useful, so it would be wise to use an easily-understandable set of rules for your header files. Personally, I prefer to do something like this:

  1. If there are already any established guidelines, follow them to prevent confusion.
  2. If all source files in the project are for the same language, use .h. There's no ambiguity.
  3. If some headers are compatible with multiple languages, while others are only compatible with a single language, extensions are based on the most restrictive language that a header is compatible with. A header compatible with C, or with both C & C++, gets .h, while a header compatible with C++ but not C gets .hpp or .hh or something of the sort.

This, of course, is but one of many ways to handle extensions, and you can't necessarily trust your first impression even if things seem straightforward. For example, I've seen mention of using .h for normal headers, and .tpp for headers that only contain definitions for templated class member functions, with .h files that define templated classes including the .tpp files that define their member functions (instead of the .h header directly containing both the function declaration and the definition). For another example, a good many people always reflect the header's language in its extension, even when there's no chance of ambiguity; to them, .h is always a C header and .hpp (or .hh, or .hxx, etc.) is always a C++ header. And yet again, some people use .h for "header associated with a source file" and .hpp for "header with all functions defined inline".

Considering this, the main advantage would come in consistently naming your headers in the same style, and making that style readily apparent to anyone examining your code. This way, anyone familiar with your usual coding style will be able to determine what you mean with any given extension with just a cursory glance.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top