extern keyword and structures

This is a discussion on extern keyword and structures within the C Programming forums, part of the General Programming Boards category; Hi folks, I understand the use of extern for different type objects, but I'm having trouble using extern on a ...

  1. #1
    Registered User
    Join Date
    Jan 2002
    Posts
    7

    extern keyword and structures

    Hi folks,

    I understand the use of extern for different type objects, but I'm having trouble using extern on a global structure from one file in another file.

    file1.c declares and defines:

    struct FREQ{
    int a;
    char str_freq[MAX_FREQ_STRING_SIZE];
    }freq = {0," "};

    struct FREQ *p_freq = &freq;


    file2.h has:

    extern struct FREQ freq;
    extern struct FREQ *p_freq;

    file2.c has:

    freq.a = 1;

    If I comment out the line in file2.c above, everything compiles fine.

    Without file2.c/.h in the project, I can use this structure in any function in file1.c fine, but if I compile with file2.c/.h in the project, I get a compiler error: unknown size of struct or union .


    If I bring the whole structure declaration to file2.h and declare it as extern as follows:

    extern struct FREQ{
    int a;
    char str_freq[MAX_FREQ_STRING_SIZE];
    }freq;

    I get a compiler error: redefinition tag of struct FREQ
    even though it's declared as extern.

    I have no problem with external int, char...etc.., but this external structure declaration is giving me fits.
    I'm missing something here, can anyone help me?

    Thanks alot in advance.

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    extern struct FREQ{
    int a;
    char str_freq[MAX_FREQ_STRING_SIZE];
    }freq;
    This is invalid. You don't declare this this way. What you need is a header file with the definition of the structure in it:

    MYHEADER.H
    struct FREQ {
    int a;
    char str_freq[MAX_FREQ_STRING_SIZE];
    };


    Now then, in file1, you have:

    struct FREQ someVar;

    And in file2, to access it, you use:

    extern struct FREQ someVar;

    Then, for both of them, you use the header defining the structure type.

    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Registered User
    Join Date
    Jan 2002
    Posts
    7
    Thanks,

    Yes you are so right. The thing that kept getting me was that I could declare other types as extern such as:

    extern int a;
    extern char b;

    The difference is that the compiler can see the type in this extern declaration.


    Thanks again.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. pointers and structures
    By stormbringer in forum C Programming
    Replies: 11
    Last Post: 07-24-2002, 04:09 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21