When including a C++ header file from an Objective-C header file it has compiling error, iostream not found

StackOverflow https://stackoverflow.com/questions/23455354

Question

TestViewController.h/TestViewController.mm

HelloWorld.h/HelloWorld.cpp

If I include "HelloWorld.h" into TestViewController.mm it compiles well. When I include "HelloWorld.h" into TestViewController.h it prompts an error: 'iostream' file not found.

My HelloWorld.h code is a simple standard cpp file.

#ifndef __MixedCppTest__HelloWorld__
#define __MixedCppTest__HelloWorld__

#include <iostream>
#include <vector>

class HelloWorld {


public:
    HelloWorld();
    ~HelloWorld();
};
#endif /* defined(__MixedCppTest__HelloWorld__) */
Was it helpful?

Solution 2

When I include "HelloWorld.h" into TestViewController.h it prompt error: 'iostream' file not found….

Is there any Objective-C files which imports TestViewController.h? At the stage of preprocessing header file becomes a part(along with the source file) of a translation unit, and if you're asking to include such header (with c++ libraries inclusion and c++ class definition) to Objective-C source file - then no, it's impossible. If you searching a way to compile and link .cpp and .m source files to one binary, you could make .mm wrapper unit to wire them together.

OTHER TIPS

you can use macros

#ifdef __cplus
 // TODO Code
#endif

Reference: Link

Thanks https://stackoverflow.com/users/635608/mat 's answer.

It has only one standard solution, that's make compiler knows about specified sources should be compiled as objective-c++.

There are only 3 ways:

  1. change .m to .mm

  2. change Type to Objective-c++ in Utilities panel in xcode editor.

  3. change "Compile sources as" to objective-c++

If you import cpp file indirectly, you should change all files to objective-c++ compiled mode on the import chain.

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