[英]Import .CPP files from a working iOS project and rename to .mm issue
[英]xcode ios project , how to import cpp code files from other directory?
我试着把CPP代码放在一个文件夹中统一管理,
并提供给Android和iOS平台编译使用。
我在网上搜索了几个例子,
但他们都没有提供详细的步骤。
我的实验的目录结构如下:
TestCppCrossPlatorm
|---AndroidDemo // for AndroidStudio to create a AndroidDemo
|
|---CommonCPP // cpp files
|---Core.h
|---Core.cpp
|---myMath
|---NumAdd.h
|---NumAdd.cpp
|
|---iOS_Demo // for Xcode to create a iOS project
AndroidDemo
|---app
|---src
|---main
|---cpp
|---CMakeLists.txt
|---native-lib.cpp
|---java
|---res
AndroidStudio创建的一个demo工程,我在CMakeFiles.txt
配置添加CommonCPP
代码文件如下:
include_directories(../../../../../CommonCPP)
add_library( # Sets the name of the library.
native-lib
# Sets the library as a shared library.
SHARED
# Provides a relative path to your source file(s).
native-lib.cpp
../../../../../CommonCPP/Core.h
../../../../../CommonCPP/Core.cpp
../../../../../CommonCPP/myMath/NumAdd.h
../../../../../CommonCPP/myMath/NumAdd.cpp
)
编辑native-lib.cpp
:
#include "Core.h" // test cpp code : Core.h
#include "myMath/NumAdd.h" // test cpp code : NumAdd.h
extern "C" JNIEXPORT jstring JNICALL
Java_sodino_demo_MainActivity_stringFromJNI(
JNIEnv* env,
jobject /* this */) {
// code to try : it's ok!
std::string addResult = std::to_string(add(2, 3));
const char* result = concatenateMyStringWithCppString(addResult.c_str());
// std::string hello = "Hello from C++";
return env->NewStringUTF(result);
}
代码运行良好,演示也运行正常。
iOS项目的配置存在一些问题
Xcode 在文件夹 iOS_Demo 中创建了一个 iOS 演示项目,
首先,我通过路径Build Settings -> Targets -> Add
添加一个名为 CommonCPP for iOS_Demo 的static library
,
其次,点击CommonCPP
target,选择Build Phases -> Compile Sources -> Add
,添加CommonCPP
文件夹,如下:
编辑ViewController.mm
以添加include Core.h and myMath/NumAdd.h
,
它失败了…… 'myMath/NumAdd.h' file not found
问题 1:
为什么所有的 cpp 文件都显示在Demo_iOS
下面的 Xcode 中,而不是CommonCPP
目标?
问题2 :
为什么Core.h
可以包含,但myMath/NumAdd.h
失败? 以及如何修复它?
没有详细步骤的例子: 如何使用C++进行跨平台开发
CMAKE是一个不错的选择,但是现在,我更关心的是如何一步一步来,对。
核心文件
#ifndef __HelloCpp__Core__
#define __HelloCpp__Core__
#include <iostream>
const char *concatenateMyStringWithCppString(const char *myString);
#endif /* defined(__HelloCpp__Core__) */
核心文件
#include <string.h>
#include "Core.h"
#include "myMath/NumAdd.h"
const char *CPP_BASE_STRING = "cpp says hello to %s";
const char *concatenateMyStringWithCppString(const char *myString) {
char *concatenatedString = new char[strlen(CPP_BASE_STRING) + strlen(myString)];
sprintf(concatenatedString, CPP_BASE_STRING, myString);
return concatenatedString;
}
myMath/NumAdd.h
//
// Created by sodino on 2021/7/18.
//
#ifndef ANDROIDDEMO_NUMADD_H
#define ANDROIDDEMO_NUMADD_H
int add(int a, int b);
#endif //ANDROIDDEMO_NUMADD_H
myMath/NumAdd.cpp
//
// Created by sodino on 2021/7/18.
//
#include "NumAdd.h"
int add(int a, int b) {
return a + b;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.