Donald Duck Donald Duck - 6 months ago 38
C++ Question

How can I check if a cpp file is being compiled in an Objective C++ project using the preprocessor?

I have a C++ source file (.cpp) which is shared between two of my projects, one using Objective C++ and the other just using plain C++. I have a part of that file where I need to use different code for the Objective C++ project and for the plain C++ project, so I need to check if the project is being compiled using Objective C++ or not. After some searching, I found that the

macro can be used to check if the file is compiled by an Objective C compiler, so I tried this code:

#ifdef __OBJC__
//Objective C++ specific code here
//Plain C++ specific code here

The problem is that the
macro is never defined, not even in the Objective C++ project. I also noticed that the
macro is defined in the .mm files in the Objective C++ project, but not in the .cpp file.

In case it matters, I'm compiling the Objective C++ project for iOS with XCode, and the plain C++ project is a cross-platform computer program which can be compiled using Visual Studio, XCode or GCC.

How can I check using the preprocessor if my .cpp file is being compiled in an Objective C++ project or a plain C++ project?

Answer Source

The problem was that by default, XCode determines the file type by the extension and not by the project, so it thought that the .cpp file was a plain C++ file even though it's part of an Objective C++ project, so it didn't define the __OBJC__ macro in that file. The solution was to change the compilation mode by right clicking on the .cpp file in the file list in the left part of XCode, click on "Show File Inspector" and in the "Type" dropdown in the right side of XCode select "Objective-C++ Source" instead of "Default - C++ Source":

enter image description here

This will make XCode think that the .cpp file is an Objective C++ file so it will define the __OBJC__ macro.

Since this is a per-project setting, it only has effect on the Objective C++ project and does not change anything in the plain C++ project, so #ifdef __OBJC__ will be a way to check which project the file is being compiled in.

Thanks to Josh Caswell for giving me the idea in this comment.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download