Runtime error when compiling Objective-C project using g++ - c++

I've made a really small project using Objective-C, and If I run it with the Xcode, It works really well.
But, I need to compile it using below command lines:
g++ Main.mm -o Main `gnustep-config --objc-flags` `gnustep-config --base-libs` -O2 -DONLINE_JUDGE -DBOJ
This command line is what the site I'm trying to upload my code to compile uses to compile Objective-C projects.
But, whenever I compile whit that command line, I get runtime errors for using NSMutableArray, NSSet and NSString.
Errors:
zsh: command not found: gnustep-config
zsh: command not found: gnustep-config
Undefined symbols for architecture x86_64:
"_OBJC_CLASS_$_NSMutableArray", referenced from:
objc-class-ref in Main-49f6e3.o
"_OBJC_CLASS_$_NSSet", referenced from:
objc-class-ref in Main-49f6e3.o
"_OBJC_CLASS_$_NSString", referenced from:
objc-class-ref in Main-49f6e3.o
"___CFConstantStringClassReference", referenced from:
CFString in Main-49f6e3.o
"_objc_msgSend", referenced from:
_main in Main-49f6e3.o
"_objc_opt_new", referenced from:
_main in Main-49f6e3.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
And, here is my source code:
#import <Foundation/Foundation.h>
int main(void) {
int num = 0;
int answer = 0;
scanf("%i", &num);
NSMutableArray *cl = [NSMutableArray new];
for (int k = 0; k < num; k++) {
char str[4];
getchar();
scanf("%[^\n]s", str);
NSString *userInput = [NSString stringWithUTF8String:str];
if (userInput.length == 1) {
[cl removeObjectAtIndex:0];
} else {
[cl addObject:[userInput substringFromIndex:[userInput length] - 1]];
}
NSMutableArray *result = [NSMutableArray new];
for (int i = 1; i <= cl.count; i++) {
for (int j = 0; j <= cl.count-i; j++) {
[result addObject:[[cl subarrayWithRange:NSMakeRange(j, i)] componentsJoinedByString:#""]];
}
}
answer += [[NSSet setWithArray:result] allObjects].count;
}
printf("%d\n", answer%1000000007);
return 0;
}

Those are linker errors, not runtime errors.
You need to link against the objc library and Foundation framework. Try:
g++ Main.mm -lobjc -framework Foundation ...

Related

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

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.

linker command failed with exit code 1 (MAC MPI)

I am trying to run a simple MPI code as I am learning MPI. I am using ECLIPSE PTP platform for c++ for compiling. In linux it is working fine. Here is the code.
MPI_Init(&argc,&argv);
int num_procs;
MPI_Comm_size(MPI_COMM_WORLD,&num_procs);
int rank;
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
if(rank == 0){
cout << "Hello world" << endl;
}
MPI_Finalize();
return 0;
I'm getting this error:
Undefined symbols for architecture x86_64:
"_MPI_Comm_rank", 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)
make: *** [mpi_test] Error 1

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.

error 'Undefined symbols for architecture x86_64 ' on Xcode 6 for Objective C

I started studying Objective C using Xcode 6. so i am new to this. i follow some tutorial on Web and trying some examples. i am using mac os x 10.9. i did not get error so far like this. i have tried many objective c codes. here i attached my coding.
main.m
#import <Foundation/Foundation.h>
#import "CarUtilities.h"
int main(int argc, const char * argv[]) {
#autoreleasepool {
NSDictionary *makesAndModels = #{
#"Ford":#[#"Explorer",#"F-150"],
#"Honda":#[#"Accord",#"Civic",#"Pilot"],
#"Nissan":#[#"370Z",#"Altima",#"Versa"],
#"Porsche":#[#"911 Trubo",#"Boxter",#"Cayman S"]
};
NSString *randomCar = CUGetRandomMakeAndModel(makesAndModels);
NSLog(#"Selected a %#",randomCar);
}
return 0;
}
//CarUtilities.m
#import
#import "CarUtilities.h"
//private function declaration
static id getRandomItemFromArray(NSArray *anArray);
//public funtion implementation
NSString *CUGetRandomMake(NSArray *makes){
return getRandomItemFromArray(makes);
}
NSString *CUGetRandomModel(NSArray *models){
return getRandomItemFromArray(models);
}
NSString *CUGetRandomMakeAndModel(NSDictionary *makesAndModels){
NSArray *makes = [makesAndModels allKeys];
NSString *randomMake = CUGetRandomeMake(makes);
NSArray *models = makesAndModels[randomMake];
NSString *randomModel = CUGetRandomeModel(models);
return [randomMake stringByAppendingFormat:#" %#",randomModel];
}
//private function implementation
static id getRandomItemFromArray(NSArray *anArry){
int maximum = (int) [anArry count];
int randomIndex = arc4random_uniform(maximum);
return anArry[randomIndex];
}
CarUtilities.h
#import <Foundation/Foundation.h>
NSString *CUGetRandomeMake(NSArray *makes);
NSString *CUGetRandomeModel(NSArray *models);
NSString *CUGetRandomMakeAndModel(NSDictionary *makesAndModels);
when i try to run this code i got following errors.
Ld /Users/samudrjkumara/Library/Developer/Xcode/DerivedData/CarUtilities-govahlvyjxsayfaxlqircwemwocg/Build/Products/Debug/CarUtilities normal x86_64
cd /ObjectiveC/CarUtilities
export MACOSX_DEPLOYMENT_TARGET=10.9
/Applications/Xcode6-Beta6.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -arch x86_64 -isysroot /Applications/Xcode6-Beta6.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk -L/Users/samudrjkumara/Library/Developer/Xcode/DerivedData/CarUtilities-govahlvyjxsayfaxlqircwemwocg/Build/Products/Debug -F/Users/samudrjkumara/Library/Developer/Xcode/DerivedData/CarUtilities-govahlvyjxsayfaxlqircwemwocg/Build/Products/Debug -filelist /Users/samudrjkumara/Library/Developer/Xcode/DerivedData/CarUtilities-govahlvyjxsayfaxlqircwemwocg/Build/Intermediates/CarUtilities.build/Debug/CarUtilities.build/Objects-normal/x86_64/CarUtilities.LinkFileList -mmacosx-version-min=10.9 -fobjc-arc -fobjc-link-runtime -Xlinker -dependency_info -Xlinker /Users/samudrjkumara/Library/Developer/Xcode/DerivedData/CarUtilities-govahlvyjxsayfaxlqircwemwocg/Build/Intermediates/CarUtilities.build/Debug/CarUtilities.build/Objects-normal/x86_64/CarUtilities_dependency_info.dat -o /Users/samudrjkumara/Library/Developer/Xcode/DerivedData/CarUtilities-govahlvyjxsayfaxlqircwemwocg/Build/Products/Debug/CarUtilities
Undefined symbols for architecture x86_64:
"_CUGetRandomeMake", referenced from:
_CUGetRandomMakeAndModel in CarUtilities.o
"_CUGetRandomeModel", referenced from:
_CUGetRandomMakeAndModel in CarUtilities.o``
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
where i have gone wrong. please need a help on this as i am new to Xcode and Objective C..
I think the issue is related to Project build settings.
In your target build setting do check if under architecture subview:
"Architecture" includes all supported architectures. (including arm64)
"Build active architecture only": NO.
Not enough repo to add image. so please check the image at this post:
Xcode 5 and iOS 7: Architecture and Valid architectures
Typos:
NSString *CUGetRandomMake(NSArray *makes){
return getRandomItemFromArray(makes);
}
...
NSString *randomMake = CUGetRandomeMake(makes);
// ^
same for CUGetRandomModel().

OpenCV "referenced from: _main in main.o" build error

I am trying to run the following program in Xcode;
#include <stdio.h>
#include <stdlib.h>
#include <opencv/cv.h>
#include <opencv/highgui.h>
int TrackbarInitValue = 0;
int TrackbarStopValue;
CvCapture *capture = NULL;
IplImage *frame;
void onTrackbarSlide(int position)
{
cvSetCaptureProperty(capture, CV_CAP_PROP_POS_FRAMES, position);
// cvShowImage("Trackbar", frame);
}
int main(int argc, char **argv)
{
cvNamedWindow("Trackbar", CV_WINDOW_AUTOSIZE);
if(argc < 2)
{
printf("Please specify the video name n");
exit(0);
}
capture = cvCreateFileCapture(argv[1]);
TrackbarStopValue = (int) cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_COUNT);
if(TrackbarStopValue != 0)
{
cvCreateTrackbar("Position", "Trackbar", &TrackbarInitValue, TrackbarStopValue, onTrackbarSlide);
}
while(1)
{
frame = cvQueryFrame(capture);
if(!frame) break;
int pos = (int) cvGetCaptureProperty(capture, CV_CAP_PROP_POS_FRAMES);
cvSetTrackbarPos("Position", "Trackbar", pos);
cvShowImage("Trackbar", frame);
char c = cvWaitKey(33);
if( c == 27) break;
}
cvReleaseCapture(&capture);
cvDestroyWindow("Trackbar");
return 0;
}
And when I try to build, I get the following errors;
Ld build/Debug/TrackBarPlayer normal x86_64
cd "/Users/facebooth/C++ practice/OpenCV Practice/TrackBarPlayer"
setenv MACOSX_DEPLOYMENT_TARGET 10.6
/Developer/usr/bin/g++-4.2 -arch x86_64 -isysroot /Developer/SDKs/MacOSX10.6.sdk "-L/Users/facebooth/C++ practice/OpenCV Practice/TrackBarPlayer/build/Debug" -L/opt/local/lib "-F/Users/facebooth/C++ practice/OpenCV Practice/TrackBarPlayer/build/Debug" -filelist "/Users/facebooth/C++ practice/OpenCV Practice/TrackBarPlayer/build/TrackBarPlayer.build/Debug/TrackBarPlayer.build/Objects-normal/x86_64/TrackBarPlayer.LinkFileList" -mmacosx-version-min=10.6 -o "/Users/facebooth/C++ practice/OpenCV Practice/TrackBarPlayer/build/Debug/TrackBarPlayer"
Undefined symbols:
"_cvCreateFileCapture", referenced from:
_main in main.o
"_cvSetCaptureProperty", referenced from:
onTrackbarSlide(int) in main.o
"_cvNamedWindow", referenced from:
_main in main.o
"_cvSetTrackbarPos", referenced from:
_main in main.o
"_cvCreateTrackbar", referenced from:
_main in main.o
"_cvShowImage", referenced from:
_main in main.o
"_cvQueryFrame", referenced from:
_main in main.o
"_cvDestroyWindow", referenced from:
_main in main.o
"_cvReleaseCapture", referenced from:
_main in main.o
"_cvWaitKey", referenced from:
_main in main.o
"_cvGetCaptureProperty", referenced from:
_main in main.o
_main in main.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
I'm a complete newbie to programming, and after literally hours of Googling, all I have discovered is that it's a linking problem. If anyone could give me some guidance on how to fix it, or what these errors are even actually saying, it would be very much appreciated.
link libopencv_videoio.3.2.6.dylib