簡體   English   中英

如何從Android NDK中的另一個C ++文件讀取常量

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

我在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());
}


編輯

這是我的方法

我的本機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());
}


我的常數

#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

constants.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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM