外部函数输出与C ++中的预期不符

时间:2019-05-21 04:23:15

标签: c++ variables header extern

我一直在尝试使用“ 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;

}

实际输出:

hello a is 746

预期输出:

hello a is 746
hi 746

2 个答案:

答案 0 :(得分:0)

test1.cpp

#include "test1.h"
int a = 745; //< don't need extern here
void print() { //< or here

    cout << "hi "<< a <<endl;
}

test2.cpp

#include"test1.h"
/* we don't need to redefine the externs here - that's
 what the header file is for... */
int b = ++a;
int main()
{
    cout << "hello a is " << b << endl;
    print(); //< don't redeclare the func, call it instead
    return 0;
}

答案 1 :(得分:0)

仅在声明变量/函数时才需要使用extern,并在其中一个cpp文件(包括标题)中定义变量。

所以,您要做的是

test1.h

#pragma once
#include<iostream>
using namespace std;
extern int a;
extern void print();

test1.cpp

#include "test1.h"
int a = 745;
void print() {

    cout << "hi "<< a <<endl;
}

test2.cpp

#include"test1.h"
int b = ++a;
int main()
{
    cout << "hello a is " << b << endl;
    print();
    return 0;

}