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

Source: Internet
Author: User

(i) extern in the header file usage
Because the header file is contained in more than one source file, and the definition of the variable can only occur once, in the header file, you can only declare that no definition can occur. We can declare global variables in the header file with extern, so that the declared global variable (such as variable A in the following program) can be used directly in the CPP containing this header file.
But there are three exceptions:
1. Class can be defined in the header file
2. Const object that value is known at compile time

3. You can define the inline function

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

mine.h#include <iostream>extern int a;const int b = 2;//int C;   Error hint repeating definition//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 (if local cannot be used in another CPP) int main () {cout << a << "" << b << endl;return 0;}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

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.