サーチ…


備考

出典: 定義と宣言の違いは何ですか?

ソース(弱く強いシンボルの場合): https : //www.amazon.com/Computer-Systems-Programmers-Perspective-2nd/dp/0136108040/

宣言と定義の理解

宣言は識別子を導入し、型、オブジェクト、関数などの型を記述します。宣言は、コンパイラがその識別子への参照を受け入れる必要があるものです。これらは宣言です:

extern int bar;
extern int g(int, int);
double f(int, double); /* extern can be omitted for function declarations */
double h1();           /* declaration without prototype */
double h2();           /* ditto                         */

定義は実際にこの識別子をインスタンス化/実装します。これらのエンティティへの参照をリンクするためにリンカが必要とするものです。これらは上記の宣言に対応する定義です。

int bar;
int g(int lhs, int rhs) {return lhs*rhs;}
double f(int i, double d) {return i+d;}
double h1(int a, int b) {return -1.5;}
double h2() {}  /* prototype is implied in definition, same as double h2(void) */

宣言の代わりに定義を使用することができます。

ただし、これは正確に1回定義する必要があります。宣言され、どこかで参照されているものを定義することを忘れた場合、リンカーは何を参照するかを知らず、シンボルの欠落について文句を言います。何度も何かを定義すると、リンカーは定義を参照して重複しているシンボルにリンクするかどうかを知りません。

例外:

extern int i = 0;  /* defines i */
extern int j;  /* declares j */

この例外は、「強いシンボルと弱いシンボル」(リンカの観点から)という概念を使用して説明できます。詳しい説明はこちら (スライド22)をご覧ください。

/* All are definitions. */
struct S { int a; int b; };             /* defines S */
struct X {                              /* defines X */
    int x;                              /* defines non-static data member x */
};
struct X anX;                                  /* defines anX */


Modified text is an extract of the original Stack Overflow Documentation
ライセンスを受けた CC BY-SA 3.0
所属していない Stack Overflow