3

I am working on an open-source C file containing the following declaration

static PyTypeObject Bitarraytype;

followed later by the definition

static PyTypeObject Bitarraytype = {
    /* A bunch of stuff */ 
};

I am porting this code to C++ (-std=C++2a), however the above declaration and definition is no longer allowed, as it claims error: redefinition of 'Bitarraytype'

I'm not sure what's causing this, as the first block above is only a declaration from my understanding. Why doesn't this work in C++ and how can I get around it?

Throckmorton
  • 564
  • 4
  • 17
  • For the last question (getting around it), is there a reason you cannot remove the "declaration"? (That just seems to me like the first workaround to try.) – JaMiT Mar 27 '20 at 23:57
  • 1
    Essentially a lot of the code in-between relies on the existence of the type, and the definitions of the type relies on the code in-between. I'm not the author of the code, and would like to change as little as possible to make the merge request easy. – Throckmorton Mar 27 '20 at 23:59

1 Answers1

1

The declaration you show is actually a tentative definition in C. C++ doesn't have that, so you get a multiple definition error.

The declaration should be marked extern to mark it is as declaration:

extern PyTypeObject Bitarraytype;

You'll also need to remove the static keyword, as the two are incompatible.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • Marking it as `extern` throws the new error `error: cannot combine with previous 'extern' declaration specifier`. Removing the `static` keyword resolves the error, though. – Throckmorton Mar 27 '20 at 23:39
  • Assuming the declarations are a file scope, remove the `static` keyword. – Peter Mar 27 '20 at 23:41
  • 1
    Well they were file scope, but with `extern` I would think they are global scope. It is also my understanding that all of the definitions in a C/C++ extension of Python should be `static` – Throckmorton Mar 27 '20 at 23:45
  • 1
    @walnut I think you can use anonymous namespaces to make that work: [example](http://coliru.stacked-crooked.com/a/69550f76893953a8) – Miles Budnek Mar 27 '20 at 23:55
  • Don't know how I missed that. Edited. – dbush Mar 27 '20 at 23:56