Can the C language define global variables in the header file?

Source: Internet
Author: User

Yes, but generally the definition of a global variable is not written in the header file.

Because if multiple C source files are added header files, it is easy to cause a redefinition problem. At this point the general compiler will prompt: "Multiple definition of ... first defined here" error.

The correct approach is to define a global variable in the C source file and add a declaration of that variable to the corresponding header file . For example:

  //var.c 一个主要用于定义全局变量的c源文件     int g_a;     char g_x;   //var.h 用于声明定义的全局变量     extern int g_a;     extern char g_x;    //test.c 一个用于测试的头文件     #include <var.h>     void f()     {        g_a = 1;        g_x =  ‘x‘ ;     }

Can the C language define global variables in the header file?

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.