Question

I create C++ project in Xcode which links against the Qt framework. The hello world program works well. When I add a class derived from QObject and add the Q_OBJCET macro, there is link error.

The class is

MyObject.h

#ifndef MyObject_h
#define MyObject_h

#include <QtCore/QObject>

class MyOBject : public QObject
{
  Q_OBJECT

public:
    MyOBject();

};


#endif

MyObject.cpp

#include "MyObject.h"

MyOBject::MyOBject()
{
}

I know I should use the moc to compile the MyObject.h first and add the generated moc_MyObject.cpp to the Xcode project.

In Microsoft Visual Studio, I can configure this header file to be compiled with moc custom tool. And add the generate cpp file to VS project.

But this is Xcode. My question is: Is there equivalent mean in Xcode to compile the header file including Q_OBJECT macro?

Was it helpful?

Solution 2

I didn't find how to set the custom tool for a specific header file in Xcode. I found a workaround via the build phase script (Build Phases -> Add Build Phase -> Add Run Script). I added the moc command line as script, and included the generated moc_MyObject.cpp file to MyObject.cpp. It works now.

OTHER TIPS

Here's how you do it in Xcode 6:

Select your target and in Build Rules make a new custom rule. Set the "Process" drop down to "Source files with names matching" and type in *.h next to that. Set the "Using" drop down to "Custom script:" and in the script type something close to this:

/path/to/your/Qt/bin/moc ${INPUT_FILE_PATH} -o ${DERIVED_FILE_DIR}/${INPUT_FILE_BASE}_moc.cpp

You'll have to change the path to wherever your moc executable is. Now set the "Output files" to:

${DERIVED_FILE_DIR}/${INPUT_FILE_BASE}_moc.cpp

That's it for the Custom Rule.

Now to get the headers to be compiled with this rule. While your target is still selected go to "Build Phases". Expand the "Compile Sources" section, hit the "+" button at the bottom. Find and add the header files with Q_OBJECT classes in them. Add those headers to your project first if you can't find them in there.

That's it, Xcode will then run moc on those headers and it will understand that the output from moc is a .cpp and needs to be compiled and linked into you app and do that for you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top