Volker Voecking
Volker Voecking

Reputation: 5583

Mixing Objective-C and C++ code

I have an Objective-C/C++ application which uses functionality that is provided by a C++ library.

One of the C++ classes includes an enum like this:

class TheClass
{
public:
[...]

enum TheEnum
{
    YES,
    NO,
};

[...]
};

Including (using #import -if that matters-) a header file with the above class declaration in an Objective-C/C++ source file (*.mm) will make the compile fail since the preprocessor will replace "YES" by the term "(BOOL) 1" (and likewise "NO" by "(BOOL) 0").

Is there a way to fix that without renaming the values of the enum?

Upvotes: 4

Views: 775

Answers (2)

xtofl
xtofl

Reputation: 41519

YES and NO are predefined constants in Objective-C, declared in the objc.h header.

You should be able to prevent the preprocessor to expand the "YES" and "NO" macro's. This can be done by locally #undeffing them.

But technically, if you're using a language keyword as an identifier, you can expect trouble. You won't write a class containing a member called MAX_PATH, would you?

Upvotes: 5

Meredith L. Patterson
Meredith L. Patterson

Reputation: 4921

The #import does matter -- C++ headers in an Objective-C++ source file should be included with #include. I think, though am not 100% sure, that the choice of include directive (#include vs #import) determines which preprocessor is used.

You could also reverse the declaration of the constants in the enum, since by default, members of an enum are associated with integers starting from 0.

Per comments, I'm wrong. Looks like you'll have to rewrite the enum. Sorry :(

Upvotes: -1

Related Questions