在c ++中使用extern关键字作为用户定义的类型

Des*_*tor 5 c++ extern

我想extern对用户定义的类型使用关键字.这意味着我已经在一个文件中声明了对象并在其他文件中定义了它.我已经读过extern关键字用于声明变量而不定义它.当程序被拆分为多个源文件并且每个都需要使用全局变量时,extern关键字很有用.如果我错了,请纠正我.

这是我写的程序,但不幸的是我做错了什么或遗漏了一些东西,所以我得到了编译错误.

Prog1.cpp

#include <iostream>
using std::cout;
class test
{
     public:
     void fun();
};
void test::fun()
{
    cout<<"fun() in test\n";
}
test t; 
Run Code Online (Sandbox Code Playgroud)

Prog2.cpp

#include <iostream>
using std::cout;
extern test t;
int main()
{
    t.fun();
}
Run Code Online (Sandbox Code Playgroud)

现在我编译这两个使用时

g++ -o prog1.cpp prog2.cpp

编译器在prog2.cpp中给出了以下错误

error: 'test' does not name a type

error:  't' was not declared in this scope
Run Code Online (Sandbox Code Playgroud)

请帮我知道我在这里做错了什么.

Naw*_*waz 5

extern告诉编译器的定义t是别的地方,但是编译器仍然需要的defintiion test,因为你正在使用t.fun()编译 Prog2.cpp.

所以,解决的办法是,写test.h在其中定义类,然后定义test tProg2.cpp像往常一样.包括test.h在你的中,Prog2.cpp以便它可以知道的定义test.然后建立它.

test.h:

#include <iostream>

using std::cout;

class test  //definition of test
{
     public:
     void fun()
     {
        cout<<"fun() in test\n";
     }
};
Run Code Online (Sandbox Code Playgroud)

Prog1.cpp:

#include "test.h"

test t;  //definition of t
Run Code Online (Sandbox Code Playgroud)

Prog2.cpp:

#include <iostream>

#include "test.h"

using std::cout;

extern test t; //the definition of t is somewhere else (in some .o)
               //and the definition of test is in test.h
int main()
{
    t.fun();
}
Run Code Online (Sandbox Code Playgroud)

现在你的代码应该编译和链接.

请注意t链接器在链接时需要定义,因此它将在其他.o文件中搜索它,但test编译器在编译时需要定义.

现在显而易见的是,您可以将extern test t;标题本身放入标题中,这样就不必在每个.cpp要使用文件中定义的对象的文件中编写它Prog1.cpp(Prog1.o由编译器转换).

  • 谢谢.这是我的错误,我忘了在使用-o选项时提及exe文件的新名称.我错误地写了g ++ -o Prog1.cpp Prog2.cpp.再次感谢您的宝贵帮助. (2认同)