随笔 - 547  文章 - 213 评论 - 417 阅读 - 107万

这篇文章解释的简单明了:

https://stackoverflow.com/questions/10422034/when-to-use-extern-in-c

This comes in useful when you have global variables. You declare the existence of global variables in a header, so that each source file that includes the header knows about it, but you only need to “define” it once in one of your source files.

To clarify, using extern int x; tells the compiler that an object of type int called x exists somewhere. It's not the compilers job to know where it exists, it just needs to know the type and name so it knows how to use it. Once all of the source files have been compiled, the linker will resolve all of the references of x to the one definition that it finds in one of the compiled source files. For it to work, the definition of the x variable needs to have what's called “external linkage”, which basically means that it needs to be declared outside of a function (at what's usually called “the file scope”) and without the static keyword.

header:

#ifndef HEADER_H

#define HEADER_H

 

// any source file that includes this will be able to use "global_x"

extern int global_x;

 

void print_global_x();

 

#endif

source 1:

#include "header.h"

 

// it needs to be defined somewhere

int global_x;

 

int main()

{

    //set global_x here:

    global_x = 5;

 

    print_global_x();

}

source 2:

#include <iostream>

#include "header.h"

 

void print_global_x()

{

    //print global_x here:

    std::cout << global_x << std::endl;

}

 

posted on   今夜太冷  阅读(250)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
历史上的今天:
2012-04-18 Web Part的Scope问题
点击右上角即可分享
微信分享提示