作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在我的 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/
我是一名优秀的程序员,十分优秀!