Thread: Multiple definitions when defining in headers.

  1. #1
    Registered User
    Join Date
    May 2010
    Posts
    120

    Multiple definitions when defining in headers.

    Hi

    conssider the following files:

    head1.h :
    Code:
    #ifndef HEAD1_H
    #define HEAD1_H
    
    struct test
    {
        int a;
    } structTest;
    
    #endif
    head1.cpp :
    Code:
    #include "head1.h"
    
    int func()
    {
        return structTest.a;
    }
    main.cpp :
    Code:
    #include <iostream>
    #include "head1.h"
    
    int main()
    {
        std::cout <<structTest.a;
    }
    my problem is, when i try to compile this program it gives me a multiple definition of structTest. How can i prevent this??

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Your header file should contain this
    Code:
    struct test
    {
        int a;
    } 
    
    extern test structTest;
    Exactly ONE .cpp file should have
    Code:
    test structTest;
    It would be better if you didn't have this kind of global variable sharing.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    May 2010
    Posts
    120
    tks that solved it

  4. #4
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    With your code, you get StructTest in head1.cpp and main.cpp. Both global. Hence linking error.
    Salem's solution simply creates one global instance and refers the other files to use that instance instead.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Header files and multiple definitions
    By sjweinberg in forum C++ Programming
    Replies: 16
    Last Post: 07-17-2009, 05:59 PM
  2. Replies: 4
    Last Post: 06-18-2005, 02:26 PM
  3. im extreamly new help
    By rigo305 in forum C++ Programming
    Replies: 27
    Last Post: 04-23-2004, 11:22 PM
  4. Prime Number Generator... Help !?!!
    By Halo in forum C++ Programming
    Replies: 9
    Last Post: 10-20-2003, 07:26 PM
  5. include question
    By Wanted420 in forum C++ Programming
    Replies: 8
    Last Post: 10-17-2003, 03:49 AM