C++対応のCヘッダファイルの書き方

2235 ワード

最近libeventのソースコードを読んで、多くのことを学びました.C++対応のCヘッダファイルの書き方がその一つです.
書き方
次はevent.hファイルのソース:
#ifndef _EVENT_H_
#define _EVENT_H_

#ifdef __cplusplus
extern "C" {
#endif

#include <event2/event-config.h>
#ifdef _EVENT_HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#ifdef _EVENT_HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#ifdef _EVENT_HAVE_STDINT_H
#include <stdint.h>
#endif
#include <stdarg.h>

/* For int types. */
#include <evutil.h>

#ifdef WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <winsock2.h>
#include <windows.h>
#undef WIN32_LEAN_AND_MEAN
typedef unsigned char u_char;
typedef unsigned short u_short;
#endif

#include <event2/event_struct.h>
#include <event2/event.h>
#include <event2/event_compat.h>
#include <event2/buffer.h>
#include <event2/buffer_compat.h>
#include <event2/bufferevent.h>
#include <event2/bufferevent_struct.h>
#include <event2/bufferevent_compat.h>
#include <event2/tag.h>
#include <event2/tag_compat.h>

#ifdef __cplusplus
}
#endif

#endif /* _EVENT_H_ */

C++に対応するために、以下の処理が行われていることがわかります.
#ifdef __cplusplus
extern "C" {
#endif
//         
#ifdef __cplusplus
}
#endif

二理解
ポイントはextern「C」.
externは、コンパイラに宣言された関数および変数がこのモジュールまたは他のモジュールで使用できることを示すC/C++言語の関数およびグローバル変数の範囲(可視性)を示すキーワードです.
extern int a;
は、通常、モジュールのヘッダファイルにおいて、他のモジュールに参照される関数およびグローバル変数をキーワードexternで宣言する.
externに対応するキーワードはstaticであり、修飾されたグローバル変数と関数は本モジュールでのみ使用できます.1つの関数または変数がこのモジュールでのみ使用可能である場合、extern「C」によって修飾されることはできません.extern「C」に修飾された変数と関数はC言語でコンパイルされ、接続されている.
三C++とC言語コンパイルの違い
関数がある場合:
void fun(int x, int y){
    return x + y
}
CとC++でコンパイルした結果は以下の通りです.
C:
C++:
ファイル名を除いて、コンパイル後のコードはそっくりであることがわかります.
これは,C++が関数リロードをサポートするために,関数名にパラメータ戻り値とパラメータリスト情報を加えているためである.
パラメータ・リストの対応関係は次のとおりです.
int->i,long->l,char->c,string->Ss
関数には役割ドメイン情報もあるので、C++で関数をコンパイルした後に対応する名前には次のような規則があります.
役割ドメイン+戻りタイプ+関数名+パラメータリスト
コードにextern"C"{}を付けると、カッコ間のコードはC言語でコンパイルされます.