C + + Primer learning notes and thinking _3---header files those things (extern)

Source: Internet
Author: User

(i) extern in the header file use method
Because header files are included in multiple source files. And the definition of the variable can only occur once, so in the header file. It is only possible to declare that a definition cannot occur.

We can declare global variables in the header file with extern so that the declared global variable can be used directly in the CPP including this header file (for example, variable A in the following program).


But there are three exceptions:
1. Can define class in header file
2. Const object that value is known at compile time

3. Ability to define inline functions

extern int ival; Yesextern int ival=1; Errorint ival; errorconst int ival = 3; Yes
(ii) Use of head file protectors to avoid multiple including
#ifndef detects if the specified preprocessor variable is undefined. #define接受一个名字并定义改名字为预处理器变量.

#endif代表处理的边界.

mine.h#include <iostream>extern int a;const int b = 2;//int C;   The error hint repeatedly defines//hello.cpp#include "mine.h" int f (int x) {return a++;} Amin.cpp#ifndef Test//detects if the specified preprocessor variable does not define a # define TEST//definition preprocessor variable # include "Mine.h" #endif    //endusing namespace std ; int a = 2; extern is for global variables (assuming local cannot be used in a CPP) int main () {cout << a << "" << b << endl;return 0;}


C + + Primer learning notes and thinking _3---header files those things (extern)

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.