如何在结构体上使用 extern 关键字

发布于 2024-10-02 14:34:06 字数 637 浏览 0 评论 0原文

请帮助我~ :)

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

-小熊_ 2024-10-09 14:34:06

Test 是一种数据类型,因此您不需要使用 extern。正如错误消息所示,extern 仅适用于函数和对象。如果 Visual Studio 允许编译您的代码,那么这就是编译器中的“错误”。

extern 的目的是告诉编译器不要担心它看不到的函数和对象,因为它们已在其他地方定义(这些将由链接器解析)。这对于数据类型没有意义;编译器需要知道数据类型才能生成正确的目标代码。

Test is a data-type, so you don't need to use extern. 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.

流殇 2024-10-09 14:34:06

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文