简体   繁体   中英

how to use extern keyword on struct

Please Help Me~ :)

Under code complie successful on visual studio. but, Under code could not complie on linux, g++.

The code..

Ah

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(); };

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.

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.

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 bo */

and compile main file something like below

g++ bo a.cpp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM