Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile errors with C++ static library include in Swift project

I created a static library that includes the follow C++ files:

//TestClass.h File:
#ifndef TESTCLASS_H_
#define TESTCLASS_H_

using namespace std;
#include <string>

class TestClass
{
public:
   TestClass();

   virtual ~TestClass();

   int sum(int x, int y) const;
   string chain(const string& x, const string& y) const;
};


#endif /* TESTCLASS_H_ */




//TestClass.cpp File:
#include<iostream>
#include "TestClass.h"

TestClass::TestClass()
{
}

TestClass::~TestClass()
{
}

int TestClass::sum(int x, int y) const
{
   return x+y;
}

//Test.cpp File:
string TestClass::chain(const string& x, const string& y) const
{
   return x+y;
}

int main(int argc, char* argv[])
{
   TestClass test;
   cout << "1+1 = " << test.sum(1,1) << endl;
   cout << "Dog+Cat = " << test.chain("Dog","Cat") << endl;
   return 0;
}

I added

-x objective-c++

flag in "Compile Source" and

-lstdc++

flag in "Info.plist Other Preprocessor flags".

When I link my just created static library (with Objective C wrapper files), I receive the 4 follow errors, that I don't have any idea how to fix it:

Undefined symbols for architecture arm64:
  "vtable for __cxxabiv1::__class_type_info", referenced from:
      typeinfo for TestClass in libPredictionComplete.a(TestClass.o)
  NOTE: a missing vtable usually means the first non-inline virtual member function has no definition.
  "operator delete(void*)", referenced from:
      TestClass::~TestClass() in libPredictionComplete.a(TestClass.o)
  "___gxx_personality_v0", referenced from:
      -[CppObject init] in libPredictionComplete.a(CppObject.o)
      -[PredictionComplete init] in libPredictionComplete.a(PredictionComplete.o)
      -[PredictionComplete chain::] in libPredictionComplete.a(PredictionComplete.o)
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I'll appreciate any ideas about.

like image 996
Tatiana Avatar asked Mar 17 '26 18:03

Tatiana


1 Answers

From my experience, Xcode will fail to link against C++ libraries when there are no C++ sources present in the top-level project. This is also true in pure Obj-C projects as well where you are linking against static libraries that have C++ code.

A less invasive solution is to simply include an empty C++ source file in your project (here's an example cpp stub) that is "compiled" into the final .app binary. It actually doesn't emit any code, but it makes Xcode aware that there is C++ code present, causing C++ libraries to be linked in.

The advantage of this solution is it avoids modifying the project settings in Xcode, so no need to add special linker flags to force Xcode to do the right thing.

like image 115
walter Avatar answered Mar 19 '26 07:03

walter