如何在结构体上使用 extern 关键字
请帮助我~ :)
在 Visual Studio 上代码编译成功。但是,下面的代码无法在linux、g++ 上编译。
代码..
啊
struct Test { Test(); ~Test(); };
Bh
extern struct Test { Test(); ~Test(); };
A.cpp
#include "A.h"
Test::Test()
{
cout << "Construction" << endl;
}
Test::~Test()
{
cout << "Destruction" << endl;
}
B.cpp
#include "B.h"
strcut A_Test : Test { A_Test(); ~A_Test(); };
当我在linux上编译代码时。我在描述下遇到错误。
“只能为对象和函数指定存储类”
这段代码在linux上有什么问题?
谢谢大家,请理解我的傻瓜英语。
Please Help Me~ :)
Under code complie successful on visual studio. but, Under code could not complie on linux, g++.
The code..
A.h
struct Test { Test(); ~Test(); };
B.h
extern struct Test { Test(); ~Test(); };
A.cpp
#include "A.h"
Test::Test()
{
cout << "Construction" << endl;
}
Test::~Test()
{
cout << "Destruction" << endl;
}
B.cpp
#include "B.h"
strcut A_Test : Test { A_Test(); ~A_Test(); };
When I compiled code on linux. I got an error under description.
"a storage class can only be specified for objects and functions"
What is the problem this code on linux?
Thank you, all and plz understand my fool english.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Test
是一种数据类型,因此您不需要使用extern
。正如错误消息所示,extern
仅适用于函数和对象。如果 Visual Studio 允许编译您的代码,那么这就是编译器中的“错误”。extern 的目的是告诉编译器不要担心它看不到的函数和对象,因为它们已在其他地方定义(这些将由链接器解析)。这对于数据类型没有意义;编译器需要知道数据类型才能生成正确的目标代码。
Test
is a data-type, so you don't need to useextern
. As the error message says,extern
is only for functions and objects. If Visual Studio is allowing your code to compile, then that's a "bug" in the compiler.The point of
extern
is to tell the compiler not to worry about functions and objects that it cannot see, because they've been defined elsewhere (these will be resolved by the linker). This doesn't make sense for data-types; the compiler needs to know the data-type in order to generate correct object code.extern 用法的示例是
a.cpp
struct test myObj;
b.cpp
extern struct test myObj;
extern 意味着编译器不会做任何事情,它会使该符号为未定义,它只是将其留给链接器来完成其余的工作,请记住,当您编译 b.cpp 时,请为 gcc 提供 -c 选项, -c 选项 make确保代码仅编译而不链接,如下所示
g++ -c b.cpp /* 这将生成 bo */
并编译主文件,如下所示
g++ bo a.cpp
Example of extern usage is
a.cpp
struct test myObj;
b.cpp
extern struct test myObj;
extern means that compiler will not do anything,it will make that symbol as undefined, it just leaves it to the linker to do rest of the work,remember that when you compile b.cpp give -c option to gcc, -c option make sure that code is only compiled and not linked, something like below
g++ -c b.cpp /* this will generate b.o */
and compile main file something like below
g++ b.o a.cpp