Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiling .cpp file as Objective-C++ via binding.gyp when building Node.js/Node-webkit addons

I have an preexisting C++ static library that I am porting over to be compilable as an addon for Node.js / Node-webkit. To build this addon I am running node-gyp / nw-gyp on a binding.gyp file I have created. This static library is multiplatform, and compiles for Windows, Mac, and Linux via VisualStudio, Xcode and CMake, respectively. This static library is already used in a variety of applications (read, it is likely not going to be refactored just for this one case of addon compilation - which is still in the proof of concept phase).

All of the crossplatform C++ files have the .cpp file extension, even though some of them are actually compiled on Mac as Objective-C++ (so as to leverage some Cocoa niceties). In Xcode on Mac, I am able to compile such .cpp files as Objective-C++ by switching the 'type' for the file from 'Default - C++ Source' to 'Objective-C++ Source' in the 'File Inspector'. This is convenient as I am able to have the self-same file compile as C++ on Windows/Linux and Obj-C++ on Mac, regardless of the .cpp file extension. To build the addon, I am using the ObjectWrap paradigm. In order to wrap the Objective-C++ classes I must include their .h files, which forces the Objective-C++ scenario at the addon level.

I am rather new to using node-gyp and nw-gyp. Is there any additional qualifiers I can add to my binding.gyp file to explicitly denote that a given .cpp file should actually be compiled as Objective-C++, similar to the 'type' setting in Xcode I mentioned above? As an interim step while building out a proof of concept, I am successfully able to get .mm files to compile as Objective-C++. However as also alluded to above, many of these files are actually multiplatform and should compile as straight C++ on Windows/Linux once I move my proof of concept onto the other platforms, and so I would much prefer they keep the .cpp file extension.

like image 379
jbodinet Avatar asked Jan 22 '26 09:01

jbodinet


1 Answers

To compile all .cpp files as Objective-C++ add the following to binding.gyp:

'conditions': [
    ['OS=="mac"', {
        'xcode_settings': {
            'OTHER_CFLAGS': [
                '-ObjC++'
            ]
        }
    }]
]

If you need to compile only some .cpp files as Objective-C++ create a .mm file that only includes the .cpp files that should be compiled as Objective-C++. In binding.gyp use conditions to compile the .mm wrapper file or the .cpp files depending on the platform.

In file.mm:

#include "file.cpp"

In binding.gyp:

'conditions': [
    ['OS=="mac"', {
        'sources': [
            "file.mm"
        ]
    }],
    ['OS=="win"', {
        'sources': [
            "file.cpp"
        ]
    }]
]
like image 55
2 revs Avatar answered Jan 26 '26 09:01

2 revs