Thread: why Multiple define error ...

  1. #1
    Registered User
    Join Date
    Oct 2006
    Posts
    10

    Post why Multiple define error ...

    hi,

    i have created a header file with guard and it looks like

    somehead.h as

    .
    .
    some #defines
    .
    .
    const long int slim_nil = 0;
    const long int SLIM_INT_MIN = (-2147483647-1);
    .
    .
    .

    and i have included this header file in two c files and thru their corresponding header

    files

    say ...1.c includes 1.h which includes somehead.h and
    ...2.c includes 2.h which includes somehead.h, now while i compiling these 1.c and 2.c file
    together in gcc i receive error as

    /tmp/cciaeWli.o(.rodata+0x0): multiple definition of `slim_nil'
    /tmp/cc0QuOGU.o(.rodata+0x0): first defined here
    /tmp/cciaeWli.o(.rodata+0x4): multiple definition of `SLIM_INT_MIN'
    /tmp/cc0QuOGU.o(.rodata+0x4): first defined here
    /tmp/cciaeWli.o(.rodata+0x8): multiple definition of `SLIM_INT_MAX'

    but here i wonder, why it is not saying multiple defines for the #defines
    whats wrong!

    Sorry!, if it is something silly that i dont know...

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    macros (created with #define) are expanded by the preprocessor doing text substitution. They never exist as symbols in an executable, so the linker has no reason to complain.

    With integer definitions like;
    Code:
    const long int slim_nil = 0;
    a const int is declared and defined. If you place that in a header file that is #include'd in multiple source files, those source files are compiled into object files and each object file has a copy. The linker sees the variable definition in multiple object files, and complains about multiple definitions.

    The fix is to use;
    Code:
    extern const long int slim_nil;  /*  A declaration, not a definition */
    in your header file. And in EXACTLY one source file in your project which #include's that header, place this somewhere AFTER the #include directive.
    Code:
    const long int slim_nil = 0;   /*  Corresponding definition */

  3. #3
    Registered User
    Join Date
    Oct 2006
    Posts
    10
    Thanks grumpy ...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Testing some code, lots of errors...
    By Sparrowhawk in forum C Programming
    Replies: 48
    Last Post: 12-15-2008, 04:09 AM
  2. Quantum Random Bit Generator
    By shawnt in forum C++ Programming
    Replies: 62
    Last Post: 06-18-2008, 10:17 AM
  3. ras.h errors
    By Trent_Easton in forum Windows Programming
    Replies: 8
    Last Post: 07-15-2005, 10:52 PM
  4. pointer to array of objects of struct
    By undisputed007 in forum C++ Programming
    Replies: 12
    Last Post: 03-02-2004, 04:49 AM
  5. FAQ: Directional Keys - Useing in Console
    By RoD in forum FAQ Board
    Replies: 38
    Last Post: 10-06-2002, 04:42 PM