Understanding Declaration and Definition

suggest change

A declaration introduces an identifier and describes its type, whether that identifier names a type, an object, or a function. The compiler needs a declaration to accept a use of that identifier. Before C23, a function declaration with empty parentheses is not a prototype: it does not say what the parameters are. C23 treats those empty parentheses as (void). These are declarations:

extern int bar;
extern int g(int, int);
double f(int, double); /* extern can be omitted for function declarations */
double h1();           /* before C23: not a prototype */
double h2();           /* before C23: not a prototype */

A definition actually instantiates/implements this identifier. It’s what the linker needs in order to link references to those entities. These are definitions corresponding to the above declarations:

int bar; /* file-scope tentative definition */
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;} /* matches h1() only before C23; C23 rejects it */
double h2() { return 0.0; } /* no parameters; not a prototype before C23 */

A definition can be used in the place of a declaration.

An object or function with external linkage is defined exactly once in the program. If a referenced identifier is never defined, the linker reports an undefined reference. If it is defined more than once, the linker reports a duplicate symbol.

At file scope, int bar; above is a tentative definition. It becomes a zero-initialized external definition only when the translation unit has no other external definition of bar.

extern int i = 0;  /* definition, because it has an initializer */
extern int j;      /* declaration, not a definition */

That is a C rule about definitions, not a rule about strong and weak linker symbols. Some object formats also have weak symbols; see this lecture (slide 22) for one such format.

/* All are definitions. */
struct S { int a; int b; };             /* defines S */
struct X {                              /* defines X */
    int x;                              /* declares member x */
};
struct X anX;                                  /* defines anX */

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents