Including a file according to the platform?


#1

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?


#2

Hi, maybe you can use the platform defs?

#if JUCE_MAC
  #include "macfile.h"
#endif

More: JUCE_LINUX, JUCE_WINDOWS, JUCE_IOS, JUCE_ANDROID.

Does this help?


#3

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:

Foo.hpp

if defined (__APPLE__) && defined (__MACH__)

struct Foo {
    void doSomething();
};

#else

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

#endif

Foo.mm

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

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

#endif

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?

 

 

 


#4

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.

.mm

if defined (__APPLE__) && defined (__MACH__) 

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

#endif

.cpp

#ifndef __APPLE__ 
#ifndef __MACH__

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

#endif
#endif

#5

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:

 

Foo.cpp

#if IS_INSIDE_MM || ! JUCE_MAC

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

#endif

 

Foo.mm

#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


#6

Good idea, thanks.