Apple Mach-O Linker (Id) Error in Xcode 9.4.1 - c++

I am trying to use the MATLAB engine through C++ on Xcode 9.4.1 but I am getting an error: "Apple Mach-O Linker (Id) Error". I searched for the answer and found out that turning off the "Bitcode" might help. However, when I go to the Build Setting of Xcode, it is just not there. I highlight, that it is definitely not there, even if you search in the search bar. How can I turn it off, and if I can't, what can I do?
Undefined symbols for architecture x86_64:
"_engEvalString", referenced from:
_main in main.o
"_engOpen", referenced from:
_main in main.o
"_engPutVariable", referenced from:
_main in main.o
"_mxCreateDoubleMatrix_800", referenced from:
_main in main.o
"_mxGetPr_800", referenced from:
_main in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Here is the full code:
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "engine.h"
#define BUFSIZE 256
int main() {
Engine *ep ;
mxArray *Y = NULL, *result = NULL ;
char buffer[BUFSIZE];
double x[10] = {0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0,
8.0, 9.0};
if (!(ep = engOpen("\0"))) {
fprintf(stderr, "\nCan't start MATLAB engine\n");
return EXIT_FAILURE;
}
Y = mxCreateDoubleMatrix(1,10, mxREAL);
memcpy((void *)mxGetPr(Y), (void *)x, sizeof(x));
engPutVariable (ep, "Y", Y) ;
engEvalString(ep, "fx = Y.^2") ;
engEvalString(ep, "plot(Y,fx);");
engEvalString(ep, "f(x) = y^2") ;
engEvalString(ep, "xlabel('x');");
engEvalString(ep, "ylabel('y');");
printf("Hit return to continue\n\n");
fgetc(stdin);
return 0 ;
}
the error message

According to the error message and the link command shown in the screen grab, it is not linking to the MATLAB libraries. I don't know how to properly set up Xcode to do so.
The best you can do is follow the advice in the MATLAB documentation, which suggests using the mex command in MATLAB as follows:
mex -v -client engine <filename.cpp>
Replace <filename.cpp> with the actual source file name, of course. First change directory to the location of that source file, and the executable will be placed next to it.

Related

Xcode 11 project on MacOS not to use sin and cos in one function: undefined symbol "___sincosf_stret"

Building my libraries on Mac suddenly started to fail with Xcode Version 11.3 (11C29).
I was able to isolate one problem:
It seems that when you use sin and cos in the same function, the optimizer will use __sincosf_stret to calculate both at once.
So what did I do:
Create a new Xcode project, cmd line tool, objective-c
Change the main.m to main.mm to allow C++
Change main as:
#import <Foundation/Foundation.h>
#include <cmath>
void coordinateCalculator(float angle, float radius, float& x, float& y) {
float mySin = sin(angle);
float myCos = cos(angle);
x = radius * myCos;
y = radius * mySin;
}
int main(int argc, const char * argv[]) {
#autoreleasepool {
float myAngle = 0.0;
float theX, theY;
float radius = 100.0;
while (myAngle < 360.0) {
coordinateCalculator(myAngle, radius, theX, theY);
NSLog(#"My coordinates: %f, %f",theX,theY);
myAngle += 1.0;
}
}
return 0;
}
Building in Debug works fine, building for profile (Release version with optimization) will fail giving the following error message:
Undefined symbols for architecture x86_64:
"___sincosf_stret", referenced from:
coordinateCalculator(float, float, float&, float&) in main.o
_main in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
I'm building with:
C++: C++14, libC++
Base SDK: MacOS
Deployment target 10.14
When I change the deployment target to 10.7, the sincosf_stret is found, but I get 2 ARC errors:
Undefined symbols for architecture x86_64:
"_objc_loadClassref", referenced from:
__ARCLite__load() in libarclite_macosx.a(arclite.o)
"_objc_readClassPair", referenced from:
__ARCLite__load() in libarclite_macosx.a(arclite.o)
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Playing with the deployment SDKs give me:
10.7: 2 ARC link errors
10.10: 2 ARC link errors AND _sincosf_ret error
10.12 or higher: _sincosf_ret error
I can't belief that it is not possible to use sin/cos in one function.
Re-installing XCode solved my issue. Another developer had tried it on his system and it seemed to work. That made me decide to delete XCode and install it again. Problem is gone now. No problem with XCode itself.

Xcode adding new library

I ran into a problem I just can't fix. The problem is Im trying to add a new library to xcode and never did it before. I don't really now if the problem is library related or me adding a new library to xcode.
The Library Im trying to add is tidylib (tidy-html5).
#include <tidy.h>
#include <tidybuffio.h>
#include <stdio.h>
#include <errno.h>
int main(int argc, char **argv )
{
const char* input = "<title>Foo</title><p>Foo!";
TidyBuffer output = {0};
TidyBuffer errbuf = {0};
int rc = -1;
Bool ok;
TidyDoc tdoc = tidyCreate(); // Initialize "document"
printf( "Tidying:\t%s\n", input );
ok = tidyOptSetBool( tdoc, TidyXhtmlOut, yes ); // Convert to XHTML
if ( ok )
rc = tidySetErrorBuffer( tdoc, &errbuf ); // Capture diagnostics
if ( rc >= 0 )
rc = tidyParseString( tdoc, input ); // Parse the input
if ( rc >= 0 )
rc = tidyCleanAndRepair( tdoc ); // Tidy it up!
if ( rc >= 0 )
rc = tidyRunDiagnostics( tdoc ); // Kvetch
if ( rc > 1 ) // If error, force output.
rc = ( tidyOptSetBool(tdoc, TidyForceOutput, yes) ? rc : -1 );
if ( rc >= 0 )
rc = tidySaveBuffer( tdoc, &output ); // Pretty Print
if ( rc >= 0 )
{
if ( rc > 0 )
printf( "\nDiagnostics:\n\n%s", errbuf.bp );
printf( "\nAnd here is the result:\n\n%s", output.bp );
}
else
printf( "A severe error (%d) occurred.\n", rc );
tidyBufFree( &output );
tidyBufFree( &errbuf );
tidyRelease( tdoc );
return rc;
}
My problem is that I get the following error all the time and I just can't fix it:
Undefined symbols for architecture x86_64:
"_tidyBufFree", referenced from:
_main in main.o
"_tidyCleanAndRepair", referenced from:
_main in main.o
"_tidyCreate", referenced from:
_main in main.o
"_tidyOptSetBool", referenced from:
_main in main.o
"_tidyParseString", referenced from:
_main in main.o
"_tidyRelease", referenced from:
_main in main.o
"_tidyRunDiagnostics", referenced from:
_main in main.o
"_tidySaveBuffer", referenced from:
_main in main.o
"_tidySetErrorBuffer", referenced from:
_main in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
What I did?
I set up the header search path to "/usr/local/Cellar/tidy-html5/5.6.0/include/"
I set up the library search path to "/usr/local/Cellar/tidy-html5/5.6.0/lib/"
I also tried to set other link flags to "-ltidylib"
System?
MacOS High Sierra 10.13.4
XCode 9.4.1
Solution
You have to use "-ltidy" instead of "-ltidylib" under other Other Linker Flags
Select your target (typically the app you're building) and click on the Build Phases tab. Build phases are the different steps needed for building, such as checking dependencies, compiling, copying resources, etc. One of them is "Link Binary with Libraries", and it includes a list of libraries and frameworks that your project should link. Click on the + button to add a new item to the list, and choose the library you want to add. Then build.

Xcode gives Mach-O linker error: "_JNI_CreateJavaVM", referenced from: _main in main.o

I get this error from testing JNI:
Undefined symbols for architecture x86_64:
"_JNI_CreateJavaVM", referenced from:
_main in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Here is c++ code:
#include <jni.h>
#include <iostream>
using namespace std;
int main()
{
int res;
JavaVMInitArgs vm_args;
JavaVMOption options[3];
JavaVM *jvm;
JNIEnv *env;
jmethodID mid;
options[0].optionString = "-Djava.compiler=NONE";
options[1].optionString = "-Djava.class.path = /Users/stephen/course/test/Test";
options[2].optionString = "-verbose:NONE";
vm_args.version = JNI_VERSION_1_8;
vm_args.nOptions = 3;
vm_args.options = options;
vm_args.ignoreUnrecognized = JNI_TRUE;
res = JNI_CreateJavaVM(&jvm,(void**)&env,&vm_args);
if(res == JNI_ERR){
cout << "Error invoking the JVM";
return 1;
}
cout <<"create JVM successfully!"<<endl;
jclass cls = env->FindClass("/Users/stephen/course/Qt-project/test/Test");
if(cls != 0){
cout<<"find class successfully!" << endl;
}
mid = env->GetMethodID(cls,"sayHello","stephen");
if(mid != 0){
cout<<"Invoke method successfully!" << endl;
}
jvm->DestroyJavaVM();
return 0;
}
Here is java code:
public class Test
{
public static void sayHello(String s){
System.out.print("hello I am" + s + "\n");
}
}
I add the include path of " jdk/include; jdk/include/darwin" the project, also I add lib path of " jdk/jre/lib/server" to the project to get the libjvm.dylib. The c++ standard library of my project is libstdc++(gnu c++ standard library.
But I can't solve this problem as expected.
Take a look here for a sample code where JVM library is linked with your project:
https://github.com/mkowsiak/jnicookbook/tree/master/recipes/recipeNo028
Take a look at Makefile. Especially, here:
main: recipeNo028_main.o
ld -o lib/recipeNo028_main -L${JAVA_HOME}/jre/lib/server/ \
-ljvm \
$(MAC_OS_FLAGS) \
lib/recipeNo028_main.o
where jvm lib is linked with the code, and here:
CC=llvm-gcc
MAC_OS_FLAGS=-rpath ${JAVA_HOME}/jre/lib/server -L/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk -demangle -dynamic -arch x86_64 -macosx_version_min 10.12.0 -lSystem
where all required libs are added to your code as well. It should work. Try to compile sample code. You can find more samples here: http://jnicookbook.owsiak.org
Update
How to use arbitrary JDK version for compilation.
First, take a look at all installations you have
/usr/libexec/java_home -V
This will produce something like this
/usr/libexec/java_home -V
Matching Java Virtual Machines (4):
9, x86_64: "Java SE 9" /Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home
1.8.0_144, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home
1.8.0_111, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_111.jdk/Contents/Home
1.7.0_80, x86_64: "Java SE 7" /Library/Java/JavaVirtualMachines/jdk1.7.0_80.jdk/Contents/Home
Then, before running make, simply set JAVA_HOME to whatever you like
export JAVA_HOME=$(/usr/libexec/java_home -v 9)
Now, your code will use version that you have chosen.

Compiling libzip on Mac: Undefined symbols for architecture x86_64

I've been learning C++ and have decided to try to create a simple file reader using libzip on archive files (e.g. Word).
I’ve recently installed libzip on my Macbook using brew but I seem to keep on getting the following issue whenever I try to compile a program that uses libzip:
Undefined symbols for architecture x86_64:
"_zip_fopen", referenced from:
_main in main-918bfa.o
"_zip_open", referenced from:
_main in main-918bfa.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [a.exe] Error 1
The command I use to compile:
g++ -g main.cpp -std=c++11 -I/usr/local/Cellar/libzip/0.11.2/include -I/usr/local/Cellar/libzip/0.11.2/lib/libzip/include -L/usr/local/Cellar/libzip/0.11.2/lib -o ../a.exe
main.cpp:
#include <iostream>
#include <fstream>
#include <zip.h>
#include <zlib.h>
using namespace std;
int numArgs = 2;
int main(int argc, char** argv){
// Parse command line arguments
if(argc != numArgs){
std::cout << "Incorrect number of arguments provided.\n";
std::cout << "Command line syntax: fileReader.exe inputFile" << endl;
exit(0);
}
// Try out libzip functionality
std::string inputDocument(argv[1]);
int err = 0;
zip* z = zip_open(inputDocument.c_str(), 0, &err);
if(z == NULL) {
printf("Could not read docx file. Error code: %d", err);
exit(-1);
}
zip_file* contentTypes = zip_fopen(z, "[Content_Types].xml", ZIP_FL_UNCHANGED);
exit(0);
}
Doesn't look like your including the libzip library in the compilation command. Try adding -lzip to your g++ command

Undefined symbols for architecture x86_64:"_glutInit", referenced from:_main in main.o / Netbeans on Mac

My program is this Sierpinski Gasket. I'm using Netbeans on my MacBook Pro and I believe I have the libraries installed but maybe they are not linked correctly.
#include <iostream>
#include <stdio.h>
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#include <GLUT/glut.h>
#include <OpenGL/glext.h>
void myinit(){
glClearColor(1.0,1.0,1.0,1.0);
glColor3f(1.0,0.0,0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0,50.0,0.0,50.0);
glMatrixMode(GL_MODELVIEW);
}
void display(){
GLfloat vertices[3][2]={{0.0,0.0},{25.0,50.0},{50.0,0.0}};
int i, j, k;
int rand();
GLfloat p[2]={7.5,5.0};
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_POINTS);
for(k=0; k<5000; k++){
j=rand()*3;
p[0]=(p[0]+vertices[j][0])/2.0;
p[1]=(p[1]+vertices[j][1])/2.0;
glVertex2fv(p);
}
glEnd();
glFlush();
}
int main(int argc, char** argv) {
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(500,500);
glutInitWindowPosition(0,0);
glutCreateWindow("Sierpinski Gasket");
glutDisplayFunc(display);
myinit();
glutMainLoop();
}
Here are the compilation errors:
Undefined symbols for architecture x86_64:
"_glutInit", referenced from:
_main in main.o
"_glutInitDisplayMode", referenced from:
_main in main.o
"_glutInitWindowSize", referenced from:
_main in main.o
"_glutInitWindowPosition", referenced from:
_main in main.o
"_glutCreateWindow", referenced from:
_main in main.o
"_glutDisplayFunc", referenced from:
_main in main.o
"_glutMainLoop", referenced from:
_main in main.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status
make[2]: *** [dist/Debug/GNU-MacOSX/sierpinski] Error 1
make[1]: *** [.build-conf] Error 2
make: *** [.build-impl] Error 2
You need to link the GLUT framework. In Project Properties > Linker > Command Line > Aditional Options, specify
-framework GLUT
Slight correction in your code:
j = rand() % 3;
and not rand() * 3;. That gives seg fault for obvious reasons.
To complement #user55721's GLUT framework answer, in the context of installing JasPer.
The INSTALL doc mentions an arch specific cmake option to use native GLUT on Mac OS:
When building the JasPer software under Mac OSX, only the use of the
native framework for OpenGL is officially supported. If the Freeglut
library is installed on your system, you will need to ensure that the
native GLUT library (as opposed to the Freeglut library) is used by
the build process. This can be accomplished by adding an extra option
to the cmake command line that resembles the following:
-DGLUT_glut_LIBRARY=/System/Library/Frameworks/GLUT.framework