4

This is driving me crazy.

I have a C++ class declaration in foo.h file.

class foo // error marks are here
{
};

When I #include/#import this header in my fooUser.mm file, it compiles. When I do #include/#import it in my fooUser.h file it doesn't, and the compiler errors are.

Unknown type name 'class'; did you mean 'Class'?
Excpected ';' after top level declarator.

I'm using XCode 4.2, LLVM compiler 3.0,... should this be important.

Popeye
  • 11,839
  • 9
  • 58
  • 91
Merlevede
  • 8,140
  • 1
  • 24
  • 39
  • 2
    Is "fooUser.h" included from a non-C++ (or non-Objective-C++) file? – Martin R Feb 26 '14 at 08:15
  • 1
    Yes, currently only my **AppDelegate.h** imports **fooUser.h** – Merlevede Feb 26 '14 at 08:17
  • @Merlevede: headers generally shouldn't need to import other headers – newacct Feb 27 '14 at 01:02
  • No matter how much I tweaked I couldn't get rid of the errors, I downloaded an example from Apple (Cocoa_With_Carbon_or_CPP) and compared every single build setting, and nothing. So what I did was create a new project, added a dummy 'foo' C++ class and it worked, I've been building up from there, little by little, and it still works. But I'm still puzzled. Either I missed something very stupid, or something in the project got messed up. – Merlevede Feb 27 '14 at 19:00
  • @newacct You say "headers generally shouldn't need to import other headers" - where do you get your tyepdefs, enums, etc from? – Mawg says reinstate Monica Feb 15 '17 at 08:43
  • @Mawg: Okay, that's true. But in that case, each typedef, enum, protocol, etc. can be in a header of its own. Here, the header it imports contains a class declaration, and another header generally shouldn't import it unless it inherits from the class. – newacct Feb 18 '17 at 02:44

1 Answers1

7

As you said in a comment, "fooUser.h" is included from non-C++ files as well, and that causes the compiler error. Header files are not compiled separately, but as part of the "compilation unit" from which they are included.

You should try to separate the C++ declarations into a header file that is included only from (Objective-)C++ files.

As a workaround, you could also protect the C++ declarations by

#ifdef __cplusplus
// …
#endif
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382