[英]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.