【发布时间】:2019-05-21 04:23:15
【问题描述】:
我一直在尝试使用 'extern' 关键字做一些事情。我写了这个基本功能,但我不确定为什么我的打印功能不起作用。请帮助我理解它。
test1.h
#pragma once
#include<iostream>
using namespace std;
extern int a;
extern void print();
test1.cpp
#include "test1.h"
extern int a = 745;
extern void print() {
cout << "hi "<< a <<endl;
}
test2.cpp
#include"test1.h"
extern int a;
extern void print();
int b = ++a;
int main()
{
cout << "hello a is " << b << endl;
void print();
return 0;
}
Actual output :
hello a is 746
Expected output:
hello a is 746
hi 746
【问题讨论】:
-
来自上面的链接:"extern说明符只允许在变量和函数的声明中(类成员或函数参数除外)。它指定外部链接,技术上不影响存储持续时间,但它不能用于自动存储持续时间对象的定义中,因此所有外部对象都有静态或线程持续时间。另外,使用外部且没有初始化器的变量声明不是定义“
-
这个问题与
extern无关——如果所有代码都在同一个文件中,您将观察到相同的缺失输出。在您最喜欢的 C++ 书籍中了解如何调用函数。 -
顺便说一句:函数在 C++ 中默认为
extern。
标签: c++ variables header extern