如何将来自不同 sub-dirs 的 inter-dependent 源文件包含到 cmake 中

how to include inter-dependent source files from differnt sub-dirs into cmake

声明:我有一些 C 代码,我通常会在 Linux 上构建(使用 Makefile)和 运行。但现在我想 运行 在 Android 设备上使用相同的代码。所以这是我的方法。

public native String helloC();
TextView tv = (TextView) findViewById(R.id.hello_textview);
tv.setText(helloC());
static {    
System.loadLibrary("native-lib"); 
}

这是我的 C 代码 (native-lib.cpp):

JNIEXPORT jstring JNICALL Java_com_example_myapp_MainActivity_helloC(JNIEnv *env, jobject javaobj) {
    return env->NewStringUTF("Hello from JNI ! ");
}

我可以成功构建并且 运行 这个并且我确实在设备上看到来自 JNI 的问候。

app、config、common 和 remote 中的代码混合了 .h、.c 文件以及 sub-folders。此代码的入口点是 remote_main(),它位于 remote/remote_main.c 文件中。我的计划是在我的 native-lib.cpp 中调用 remote_main()。为此,我所有的源文件都应该是 compile-able。我在 cmakelist 中添加了 include_directories(src/main/cpp/app 等等)。

这是我的 2 个问题:

  1. 尽管我添加了 include_directories,但我看到一个错误,所有 headers 都显示 "cannot find .h" 错误
  2. 下一个问题是如何编译上述4个文件夹中的所有C文件及其sub-folders。我尝试了 this 问题中提到的方法。但问题是我的代码是相互依赖的。一个文件夹中的文件可能需要其他文件夹中的文件。所以我无法为每个文件夹创建单独的 cmake 文件并独立构建它,然后 link 它们一起构建。

这是我第一次在 Android 上使用 CMake 和 运行ning。任何 suggestion/help 表示赞赏。

CMakeLists.txt内容:

cmake_minimum_required(VERSION 3.4.1)

include_directories("src/main/cpp/app" "arc/main/cpp/config" "src/main/cpp/common" "src/main/cpp/remote")
add_library( native-lib

             SHARED

             src/main/cpp/native-lib.cpp )

find_library( log-lib log )

target_link_libraries( native-lib ${log-lib} )

您可以使用一条命令 select 所有 .c 文件并将它们添加为 "files to compile" 用于您的 native-lib 目标:

FILE(GLOB_RECURSE C_SOURCES "src/main/cpp/*.c")
add_library( native-lib
             SHARED
             src/main/cpp/native-lib.cpp
             ${C_SOURCES})
target_include_directories(native-lib PRIVATE src/main/cpp/app src/main/cpp/config src/main/cpp/common src/main/cpp/remote)

您可以使用 target_compile_definitions 添加任意编译定义:

target_compile_definitions(native-lib PRIVATE -D__FLAVOR_CLIENT)