-3

I have a struct that I want to fill out in a separate source file from where I am running main. In the header file I included the extern but when I go to define the variable in a source file it doesn't work.

    //This is a header file
    struct example {
         int data1;
         float data2;
         bool example;
    }

    extern example tmp;

And then in a source file:

example *tmp = new example;

I'm getting the error "Expected unqualified-id". Why is that?

Jude Niroshan
  • 4,280
  • 8
  • 40
  • 62
Hippity Hoopla
  • 68
  • 1
  • 10
  • Did you really look around? http://stackoverflow.com/questions/1433204/how-do-i-use-extern-to-share-variables-between-source-files-in-c here answers it good. Also I didn't get it: why are you using different data types?(ptr and var) – Lasoloz Nov 03 '15 at 05:18
  • I really did look around and already saw that. However it is not helping with this particular instance. I am using ptr because when I don't I get the error message: "no viable conversion from 'example*' to 'example'". I mentioned this in the comments on the answer as well. – Hippity Hoopla Nov 03 '15 at 15:09

1 Answers1

1
  • A semicolon is missing after the declaration of the struct.
  • The type in the extern declaration and the definition differs: example vs example*.
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • Sorry, the comma was a typo. I have the comma in my code. I removed the asterisk and now my code reads: "example tmp = new example;" however, that gets an error that reads: "no viable conversion from 'example*' to 'example'" – Hippity Hoopla Nov 03 '15 at 05:20
  • 1
    That is because `new` returns a pointer to the allocated memory! – CinCout Nov 03 '15 at 05:21
  • 1
    @phantazein Assuming comments, I must ask: do you know precisely how pointers and memory allocation work? If you don't know perfectly, try again - and this is no offense, I didn't learn in one day but I learned. Back to your question: if you create extern pointer then it's extern pointer and not (a simple) variable. So, declaring "extern example tmp" then using "example* tmp" is wrong because the first isn't pointer. Creating "extern example tmp" then allocating is wrong, since the tmp is not pointer. This means that you simply don't need to use new keyword or you should declare pointer in .h. – Lasoloz Nov 03 '15 at 16:29