Search code examples
ccompiler-errorsheaderduplicates

Compiling C project results in duplicate symbols because of header files


I am trying to compile a C project that I wrote, and a header file has some constant variables. Two .c files are including this header file, however, it results in an error of duplicate symbols.

My project structure is like: (a => b means b includes a)

common.h => struct.h
struct.h => btree.h
btree.h => btree.c && project.c

And related constants that result in an error are staying inside struct.h

How should I rebuild the project to avoid this confusion?

My constants look like:

const uint32_t NODE_TYPE_SIZE = sizeof(uint8_t);
const uint32_t NODE_TYPE_OFFSET = 0;
const uint32_t IS_ROOT_SIZE = sizeof(uint8_t);
const uint32_t IS_ROOT_OFFSET = NODE_TYPE_SIZE;
const uint32_t PARENT_POINTER_SIZE = sizeof(uint32_t);
const uint32_t PARENT_POINTER_OFFSET = IS_ROOT_OFFSET + IS_ROOT_SIZE;
const uint8_t COMMON_NODE_HEADER_SIZE =
    NODE_TYPE_SIZE + IS_ROOT_SIZE + PARENT_POINTER_SIZE;

and struct.h has these kinds of variables (around 20 more variables in addition to above) and some structs only.


Solution

  • Do not define constants in the .h files. Declare them only as extern

    example:

    extern const uint32_t NODE_TYPE_SIZE;
    

    Then define them in the .c file.

    BTW those variables do not make any sense they should be a macros instead.

    #define NODE_TYPE_SIZE sizeof(uint8_t)
    

    Same with all other similar constants. Otherwise if they have to be accessed from different compilation units, they will be stored in the memory and read from it, having negative performance impact.