Is extern keyword really necessary?

后端 未结 5 1800
鱼传尺愫
鱼传尺愫 2020-12-17 01:20
...
#include \"test1.h\"

int main(..)
{
    count << aaa <

aaa is defined in test1.h,and I didn\'t u

5条回答
  •  生来不讨喜
    2020-12-17 01:27

    I've found the best way to organise your data is to follow two simple rules:

    • Only declare things in header files.
    • Define things in C (or cpp, but I'll just use C here for simplicity) files.

    By declare, I mean notify the compiler that things exist, but don't allocate storage for them. This includes typedef, struct, extern and so on.

    By define, I generally mean "allocate space for", like int and so on.

    If you have a line like:

    int aaa;
    

    in a header file, every compilation unit (basically defined as an input stream to the compiler - the C file along with everything it brings in with #include, recursively) will get its own copy. That's going to cause problems if you link two object files together that have the same symbol defined (except under certain limited circumstances like const).

    A better way to do this is to define that aaa variable in one of your C files and then put:

    extern int aaa;
    

    in your header file.

    Note that if your header file is only included in one C file, this isn't a problem. But, in that case, I probably wouldn't even have a header file. Header files are, in my opinion, only for sharing things between compilation units.

提交回复
热议问题