0

I am using NDK in my android app . There was no problem . Here is the code for c++ file

#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


#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

#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'

mW3
  • 189
  • 3
  • 25
  • Take a look at [this](https://stackoverflow.com/a/5499530/6950238). – Andrii Omelchenko May 16 '19 at 09:50
  • I tried but didn't work , this is the error I got `constants.h:25:14: error: unknown type name 'string'; did you mean 'jstring'?` @AndriiOmelchenko – mW3 May 16 '19 at 10:02
  • _"this is the error I got"_ You're referring to code that you haven't shown us, so we can't know what you did wrong. – Michael May 16 '19 at 10:08
  • @Michael I have share my full code. – mW3 May 16 '19 at 10:32
  • Sounds like you forgot to add `constants.cpp` to the source files that should be compiled. – Michael May 16 '19 at 10:38
  • Please include the command line used to link your project. It's often shown right before the linker errors (an undefined reference is a linker error). – JaMiT May 16 '19 at 19:15
  • @Michael thanks , I really did so :( . Now my problem is solved . – mW3 May 17 '19 at 06:37

1 Answers1

1

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

#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
}
Michael
  • 57,169
  • 9
  • 80
  • 125
  • Thanks for the answer , I tried your solution , but couldn't solve . I have edited my question. Could you kindly have a look ? – mW3 May 16 '19 at 10:30