programing

#include in .h or .c / .cpp?

minecode 2022. 8. 11. 21:49
반응형

#include in .h or .c / .cpp?

C 또는 C++ 중 하나로 코딩할 때,#include의?

callback.h:

#ifndef _CALLBACK_H_
#define _CALLBACK_H_

#include <sndfile.h>
#include "main.h"

void on_button_apply_clicked(GtkButton* button, struct user_data_s* data);
void on_button_cancel_clicked(GtkButton* button, struct user_data_s* data);

#endif

callback.c:

#include <stdlib.h>
#include <math.h>

#include "config.h"

#include "callback.h"
#include "play.h"

void on_button_apply_clicked(GtkButton* button, struct user_data_s* data) {
  gint page;
  page = gtk_notebook_get_current_page(GTK_NOTEBOOK(data->notebook));

  ...

Should all includes be in either the .h or .c / .cpp, or both like I have done here?

가능한 한 많이 넣어주세요..c가능한 한 적은 양으로.h는 에 포함되어 있습니다..c1개의 파일이 컴파일 되었을 때에만 포함되지만,에는.h파일을 사용하는 모든 파일에 포함시켜야 합니다.

The only time you should include a header within another .h file is if you need to access a type definition in that header; for example:

#ifndef MY_HEADER_H
#define MY_HEADER_H

#include <stdio.h>

void doStuffWith(FILE *f); // need the definition of FILE from stdio.h

#endif

If header A depends on header B such as the example above, then header A should include header B directly. Do NOT try to order your includes in the .c file to satisfy dependencies (that is, including header B before header A); that is a big ol' pile of heartburn waiting to happen. I mean it. I've been in that movie several times, and it always ended with Tokyo in flames.

Yes, this can result in files being included multiple times, but if they have proper include guards set up to protect against multiple declaration/definition errors, then a few extra seconds of build time isn't worth worrying about. Trying to manage dependencies manually is a pain in the ass.

Of course, you shouldn't be including files where you don't need to.

Put as many includes in your cpp as possible and only the ones that are needed by the hpp file in the hpp. I believe this will help to speed up compilation, as hpp files will be cross-referenced less.

Also consider using forward declarations in your hpp file to further reduce the include dependency chain.

만약 내가#include <callback.h>, 나는 하고 싶지 않다.#include내 코드를 컴파일할 다른 헤더 파일도 많아callback.h컴파일에 필요한 모든 것을 포함해야 합니다.하지만 그 이상은 아니야.

헤더 파일에서 전달 선언을 사용할지 여부를 고려합니다(예:class GtkButton;)로 충분합니다.그 때문에, 다음의 수를 삭감할 수 있습니다.#include머리글의 지시사항(그리고 컴파일 시간과 복잡성)을 나타냅니다.

ReferenceURL : https://stackoverflow.com/questions/3002110/include-in-h-or-c-cpp

반응형