问题描述
我做了2个项目,第一个C和第二个在C ++中,具有相同的行为都工作。
I made 2 projects, the first one in C and the second one in C++, both work with same behavior.
C ++项目:
header.h
int varGlobal=7;
的main.c
#include <stdio.h>
#include <stdlib.h>
#include "header.h"
void function(int i)
{
static int a=0;
a++;
int t=i;
i=varGlobal;
varGlobal=t;
printf("Call #%d:\ni=%d\nvarGlobal=%d\n\n",a,i,varGlobal,t);
}
int main() {
function(4);
function(6);
function(12);
return 0;
}
C ++项目:
C++ project:
header.h
int varGlobal=7;
的main.cpp
#include <iostream>
#include "header.h"
using namespace std;
void function(int i)
{
static int a=0;
int t=i;
a++;
i=varGlobal;
varGlobal=t;
cout<<"Call #"<<a<<":"<<endl<<"i="<<i<<endl<<"varGlobal="<<varGlobal<<endl<<endl;
}
int main() {
function(4);
function(6);
function(12);
return 0;
}
我读了全局变量的extern 默认并用C和静态默认用C ++;那么,为什么C ++ code ++工程?
I read that global variables are extern by default and in C and static by default in C++; so why does the C++ code works?
我的意思的 INT varGlobal = 7; 的是一样的静态INT varGlobal = 7; 的,如果它是静态的话,就只能在它声明的文件中使用,对吧?
I mean int varGlobal=7; is same as static int varGlobal=7; and if it's static then it can be used only in the file it was declared, right?
推荐答案
全局变量是不是的extern
也不静态
默认情况下,C和C ++。
当一个变量声明为静态
,你把它限制为当前的源文件。如果你把它声明为的extern
,你说该变量存在,但声明别的地方,如果你没有它的其他地方声明(没有的extern
关键字),你会得到一个链接错误(未找到符号)。
Global variables are not extern
nor static
by default on C and C++.When you declare a variable as static
, you are restricting it to the current source file. If you declare it as extern
, you are saying that the variable exists, but are declared somewhere else, and if you don't have it declared elsewhere (without the extern
keyword) you will get a link error (symbol not found).
您code将打破,当你有多个源文件包括报头,在链接时,你将不得不 varGlobal
多次引用。如果你把它声明为静态
,那么它将与多个源工作(我的意思是,它会编译和链接),但是每个源都会有自己的 varGlobal
。
Your code will break when you have more source files including that header, on link time you will have multiple references to varGlobal
. If you declare it as static
, then it will work with multiple sources (I mean, it will compile and link), but each source will have its own varGlobal
.
您可以在C ++做什么,你不能在C,是变量声明为常量
的头,像这样的:
What you can do in C++, that you can't in C, is to declare the variable as const
on the header, like this:
const int varGlobal = 7;
和包括多个来源,无需在链接时摔东西。我们的想法是,以取代旧的C风格的的#define
常量。
And include in multiple sources, without breaking things at link time. The idea is to replace the old C style #define
for constants.
如果你需要一个全局变量在多个来源可见,而不是常量
,其声明为的extern
的头,并再次声明,这次没有EXTERN keywork,对源文件:
If you need a global variable visible on multiple sources and not const
, declare it as extern
on the header, and declare it again, this time without the extern keywork, on a source file:
由多个文件包含头文件:
Header included by multiple files:
extern int varGlobal;
在源文件中的一个:
int varGlobal = 7;
这篇关于在C和C静态和extern全局变量++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!