Thread: declarations, definitions and externals

  1. #1
    Registered User Drogin's Avatar
    Join Date
    Oct 2005
    Location
    Norway
    Posts
    105

    declarations, definitions and externals

    I've discussed this somewhat in the C++ part of the forum as well, but I want to discuss the subject further in C, so I made a thread here.

    The question is as simple as this:
    If I want to share a global variable over 2 source files, could I just include this headerfile in both my files?
    Code:
    #ifndef MOFF
        #define MOFF
        int test; // Global variable to be used in 2 files
    #endif
    I have compiled it, and it works.
    The question is, is it legal, and more over, is it considered ok as a programming practice?

    I guess part of the question is, is this a declaration or definition?
    Code:
    int test;
    I tried to compile the following program:
    Code:
    int test;
    int test=50;
    int test;
    
    
    int main(int argc, char *argv[]) {
      printf("%d\n", test);
      system("PAUSE");	
      return 0;
    }
    And this compiled, linked and ran..and gave me output "50".

  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
    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 Drogin's Avatar
    Join Date
    Oct 2005
    Location
    Norway
    Posts
    105
    Thanks. That helps a lot.

    And now I have to ask, why in the lords name does C allow this kind of code?
    It looks straight out messy.(yeah, I come from C++)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Unresolved Externals
    By nickname_changed in forum C++ Programming
    Replies: 10
    Last Post: 08-31-2003, 06:13 PM