Multiply defined symbols


A header file is literally substituted into your C code in place of the #include statement. Consequently, if the header file is included in more than one source file all the definitions in the header file will occur in both source files. This causes them to be defined more than once, which gives a linker error.

Solution: don’t define variables in header files. You only want to declare them in the header file, and define them (once only) in the appropriate C source file, which should #include the header file of course for type checking. The distinction between a declaration and a definition is easy to miss for beginners; a declaration tells the compiler that the named symbol should exist and should have the specified type, but it does not cause the compiler to allocate storage space for it, while a definition does allocate the space. To make a declaration rather than a definition, put the keyword ‘extern’ before the definition.

So, if we have an integer called ‘counter’ which we want to be publiclyavailable, we would define it in a source file (one only) as ‘int counter;’ at top level, and declare it in a header file as ‘extern int counter;’.

No comments:

Post a Comment