c++ extern总结

    xiaoxiao2021-03-26  24

    我们经常看到extern这个关键字在代码中,一般有两个地方: 1. 头文件中声明一个全局变量。 2.是代码中使用extern c。 1.头文件中使用

    #ifndef _XX_头文件.H #define _XX_头文件.H int A; #endif

    例如上面的代码,如果这样定义一个全局变量,那么如果这个头文件被多次引用,那么这个全局变量A就会多次被定义,所以为了解决这个问题,需要使用关键字extern。

    #ifndef _XX_头文件.H #define _XX_头文件.H int A; #endif

    完整代码如下: extern.h

    #ifndef __EXTERN_H__ #define __EXTERN_H__ extern int a; #endif

    extern.cpp

    #include "extern.h" int a = 2;

    test1.h

    #include "extern.h" #include <iostream> using namespace std; void fun1();

    test1.cpp

    #include "extern.h" #include "test1.h" void fun1() { //a = 1; cout << a << endl; }

    test2.h

    #include "extern.h" #include <iostream> using namespace std; void fun2();

    test2.cpp

    #include "extern.h" #include "test2.h" void fun2() { //a = 2; cout << a << endl; }

    main.cpp

    #include "test1.h" #include "test2.h" int main() { fun1(); fun2(); system("pause"); return 0; }
    转载请注明原文地址: https://ju.6miu.com/read-661755.html

    最新回复(0)