简体   繁体   English

如何从Android NDK中的另一个C ++文件读取常量

[英]How to read constant from another c++ file in android NDK

I am using NDK in my android app . 我在Android应用程序中使用NDK。 There was no problem . 没问题。 Here is the code for c++ file 这是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());
}


Edit 编辑

Here is my approach 这是我的方法

my native-lib.cpp 我的本机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());
}


my constants.h 我的常数

#pragma once

#include <string>

extern const std::string secret_key;        // declaration

my constants.cpp 我的constants.cpp

#include "constants.h"

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

When I compile I get the following error 编译时出现以下错误

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

You don't want to put the definition in a header file, as that could lead to multiple definitions of the same variable. 您不想将定义放在头文件中,因为这可能导致同一变量的多个定义。

But you could do something like this: 但是您可以执行以下操作:

constants.h constants.h

#pragma once

#include <string>

extern const std::string secret_key;        // declaration

constants.cpp constants.cpp

#include "constants.h"

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

main.cpp main.cpp中

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM