Extern of C-language fragmentation record

Source: Internet
Author: User

Recently I encountered a problem where a header file has a static variable and several compiled files. o, they all reference this header file, but when the variable is printed (modified), it is actually different. When the output address is printed, the address is actually different. Are two different addresses with the same variable name? How can this problem be solved ???

This variable is used by many files. But putting it in the H file is a problem...

Use extern to declare external variables. The following conditions must be met:

The generated. o file that contains the variable definition cannot be referenced. However, I used other functions in this header file.

This should be the case after the experiment. Do not use static variables, because the external needs to use extern, but cannot use static to be depressing.

The experiment is as follows:

Head1.h

 
# Include <stdio. h>
Extern IntStr_ I;

Head1.c

# Include"Head1.h"
IntStr_j =5;
IntMain (){
Printf ("Str_ I = % d \ n", Str_ I );
Func ();
Printf ("Str_ I = % d \ n", Str_ I );

}

Head2.h

 
# Include <stdio. h>
Extern IntStr_j;
IntStr_ I =1;
VoidFunc ();

Head2.c

# Include"Head2.h"
VoidFunc (){
Str_ I =999;
Printf ("Str_j = % d \ n", ++ Str_j );
}

Compilation Method:

 
Gcc-C head1.c
Gcc-C head2.c
Gcc-O main head1.o head2.o

Or

 
Gcc-C head2.c
Gcc-O main head1.c head2.o

The result is as follows:

 

$./Main

Str_ I = 1

Str_j = 6

Str_ I = 999.

Head2 resource used

Head1 resources are also used.

However, head1 cannot use head2 header files. Otherwise, it must be defined repeatedly.

Head2 cannot use the header file of head1, otherwise it is defined repeatedly.

It seems that using other people's things does not have to add header files. Function declaration is not necessary, as long as there is a corresponding in GCC. O or Lib.

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.