ZawMyoHtet ZawMyoHtet - 10 months ago 180
C++ Question

undefined reference error in Android NDK project

I want to import c++ files to my android project. Firstly, I created a project with C++ support with android studio. It provide skeleton project structure. I loaded my file via CMakeLists.text file with add_library method. I can successfully load my c++ file and able to see in Project view. When I am trying to call a method from mClient.cpp inside my native-lib.cpp, I got

undefined reference to "hello()"

error. As I didn't see any IDE warning, I can say my file is successfully loaded. But it doesn't work at compile time. I also tried to load with add_executable via cmake but it also produce the same error. Please may I know what is missing in my configuration and setting? I am new to NDK and CMake.
Thanks for you time.


#include "mClient.h"

static int hello(){
return 1;


#ifdef __cplusplus
extern "C" {

static int hello();

#ifdef __cplusplus

Here is my CMake.text file.

# Sets the minimum version of CMake required to build the native
# library. You should either keep the default value or only pass a
# value of 3.4.0 or lower.

cmake_minimum_required(VERSION 3.4.1)

# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# You can define multiple libraries, and CMake builds it for you.
# Gradle automatically packages shared libraries with your APK.

# set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -Wall -UNDEBUG")

add_library( # Sets the name of the library.

# Sets the library as a shared library.

# Provides a relative path to your source file(s).
# Associated headers in the same location as their source
# file are automatically included.
src/main/cpp/mClient.cpp )

# Searches for a specified prebuilt library and stores the path as a
# variable. Because system libraries are included in the search path by
# default, you only need to specify the name of the public NDK library
# you want to add. CMake verifies that the library exists before
# completing its build.

find_library( # Sets the name of the path variable.

# Specifies the name of the NDK library that
# you want CMake to locate.
log )

# Specifies libraries CMake should link to your target library. You
# can link multiple libraries, such as libraries you define in the
# build script, prebuilt third-party libraries, or system libraries.

target_link_libraries(native-lib android log)

I want to call hello() from my native-lib.cpp

#include <jni.h>
#include <string>
#include "mClient.h"

extern "C"
JNIEnv* env,
jobject /* this */) {

int myInt = hello();

std::string hello = "Hello from C++";
return env->NewStringUTF(hello.c_str());

Answer Source

Remove static. static means that a function will not be accessible outside its translation unit.