gpt4 book ai didi

android - 如何从android NDK中的另一个c++文件读取常量

转载 作者:行者123 更新时间:2023-11-28 04:17:55 25 4
gpt4 key购买 nike

我在我的 android 应用程序中使用 NDK。没有问题。这是c++文件的代码

#include <jni.h>
#include <string>
#include <stdio.h>


extern "C" JNIEXPORT jstring JNICALL
Java_com_examples_core_MyApplication_getKeyJNI(
JNIEnv *env,
jobject /* this */) {
std::string secret_key = "mysecret";
return env->NewStringUTF(secret_key.c_str());
}


编辑

这是我的方法

我的native-lib.cpp


#include <jni.h>
#include <string>
#include <unistd.h> // for getcwd()
#include <iostream>
#include <stdio.h>
#include "constants.h"

extern "C" JNIEXPORT jstring JNICALL
Java_com_examples_core_MyApplication_getKeyJNI(
JNIEnv *env,
jobject /* this */) {
std::string secret_key = secret_key;
return env->NewStringUTF(secret_key.c_str());
}


我的constants.h

#pragma once

#include <string>

extern const std::string secret_key; // declaration

我的constants.cpp

#include "constants.h"

const std::string secret_key = "mysecret"; // definition

编译时出现如下错误

native-lib.cpp:13: undefined reference to `secret_key'

最佳答案

您不希望将定义放在头文件中,因为这可能导致同一变量的多个定义。

但是你可以这样做:

constants.h

#pragma once

#include <string>

extern const std::string secret_key; // declaration

常量.cpp

#include "constants.h"

const std::string secret_key = "mysecret"; // definition

main.cpp

#include <iostream>
#include "constants.h"

int main()
{
std::cout << secret_key; // usage
}

关于android - 如何从android NDK中的另一个c++文件读取常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56165564/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com