简体   繁体   中英

C++: Defining void* array in header file and declaring it in a cpp file?

I saw this question and I tried to do as the answer to that question said. To use the extern keyword in the header file to define an array and then declare it outside of that namespace or class in a other cpp file.

It didn't work for me really, I'm not sure if it because I'm using a void pointer array (ie void* array[] ) or if it's just my ignorance that prevents me from seeing the problem.

This is the shortest example I can come up with:
[cpp.cpp]

#include "h.h"

void main(){
    void* a::b[] = {
        a::c = a::d(1)
    };
}

[hh]

namespace a{
    struct T* c;
    struct T* d(int e);
    extern void* b[];
}

So the problem is that I receive the error: IntelliSense: variable "a::b" cannot be defined in the current scope

And I have no clue why that is.

First, you should declare main() as int ! See here why.

Declaring your array as extern in a namespace means that it belongs to the namespace but is defined somewhere ele, normally in a separate compilation unit.

Unfortunately, in your main(), you try to redefine the element as a local variable. This explains the error message you receive.

You shoud do as follows:

#include "h.h"
void* a::b[] { a::c, a::d(1) };         // global variable belonging to namespace

int main()                  // int!!!
{
    /* your code here */  
}

The code will compile. The fact that a::b[] is defined in the same compiling unit is accepted. But the linker will complain because a::d(1) is a call to the function d returning a pointer to a struct, and this function is defined nowhere.

Therfore you should also define this:

namespace a { 
    struct T* d(int e)
    {
        return nullptr;         // in reality you should return a pointer to struct T
    }
} 

Interestingly, struct T does not need to work for this code to compile and link.

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