Including a file according to the platform?


Sorry if the response is obvious. I want to include a small Objective-C snippet. Is there a way to conditionally include “.mm” or “.cpp” file according to the platform targeted. What’s the best strategy?


Hi, maybe you can use the platform defs?

  #include "macfile.h"


Does this help?


Not really.

The file must be ".mm" in order to be compiled as Objective-C++. If i conditionally include a ".mm" file in a header, i guess it will be compiled as C++ as the project is.

For now i do that:


if defined (__APPLE__) && defined (__MACH__)

struct Foo {
    void doSomething();


struct Foo {
    void doSomething() { /* ... */ }


#if defined (__APPLE__) && defined (__MACH__)

void Foo::doSomething()
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    [pool drain];


But i'm not sure at all that is a valid approach. Maybe i'll have to force the compiler to consider the ".mm" file as C++ on other platforms. I have not tested it for now on GNU/Linux or such.

It is rather inelegant. So maybe there's a better strategy?





Then: you can have both files in your project (.mm and .cpp) and only use the code you need like the header multi include protection defines.


if defined (__APPLE__) && defined (__MACH__) 

void Foo::doSomething() { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; ... [pool drain]; }



#ifndef __APPLE__ 
#ifndef __MACH__

void Foo::doSomething() { /*cpp*/ }



If you want to write some code that has both C++ and obj-C mixed up and don't want to separate it all into mac-only and non-mac files, you can add both a .mm and a .cpp to your project like Monotomy suggested, but do this:




...all your actual code goes here or is included here, and can contain a mix of cross-platform C++ and conditionally-ifdefed obj-C


#define IS_INSIDE_MM 1
#include "Foo.cpp"

This way, the cpp will be compiled twice on mac, but will only do anything when compiled via being included in the .mm


Good idea, thanks.