NDK development from getting started to giving up (vii: Android Studio 2.2 CMAKE efficient NDK development)

Source: Internet
Author: User

Preface

Before, every time I needed to write C + + code, my heart was rejected.
1. It has no code hint!!! This means that we have to manually knock out all the code, for a novice, a letter is good and the case is correct, even remember to live all the JNI functions, etc., it is really torture ... Usually write Java code when writing a few letters will come out a lot of hints and then choose, so there is a good thing is that many times we do not know that there are those functions, but we can pass obj. , and then we can see what the method function.
2. Many places will be shown in red, just like the wrong hint of the kind, of course, if the correct words can still compile and run, but if it is like writing Java code, the wrong place to give me the red display is not better?
These two problems can torture me to this obsessive-compulsive disorder ... Baidu on the internet for a long time how to use Android studio to write C + + code when there is code hint auto-completion function, but has not been found effective (without using cmake, if someone knows, trouble to tell). Fortunately for an occasional chance to see online in Android Studio 2.2 happily using this article, see above said Android Studio2.2 version perfected the support for C + +, also mentioned to CMake, hurriedly put Android Studio upgrade from 2.0 to version 2.2, according to the introduction of a new NDK project, found that there is actually my dream of the C + + code Auto-completion prompt!!! Hi Big Ben!!!
Learn how to learn the CMake mode available under Android Studio2.2 version. Plan to use this way in the future, the other does not say, rushed can have C + + code auto-completion hint This function I fell in love with it.

Tool Installation

After upgrading to 2.2 in Android Studio, we can first configure some of the required tools developed by the NDK, and check the installation of CMake, LLDB, ndk in SDK tools.

CMake: External Build tool. If you are prepared to use only ndk-build, you can not use it.
Tools for debugging native code above lldb:android Studio.

Android Studio comes with demo to learn CMake

After upgrading to version 2.2 of Android Studio, there is one more option on the interface when creating new project Include C++ Support . Checking it will create a default C + + Java-Mixed demo program. Let's take a look at this official standard demo.

Before you start, it's a good idea to download the NDK first, see NDK development from getting started to giving up (one: Getting Started with the basic process), which is to download or select the correct path in the project structure interface at Android NDK location. Or use the tool installation method provided above to download it. Otherwise, the new project will be created with an error and need to be configured to clean.

New Project, File, New, is checked in the following screen, Include C++ Support followed by next, until Finish.

When the project opens, we look at the directory structure, which is different from the regular project. Externalnativebuild folder, CPP folder, CMakeLists.txt file, such as:

These three things are part of the NDK:
1.. externalnativebuild folder: CMake compiled file that displays information such as various supported hardware. System generation.
2. cpp folder: to store C + + code files, the Native-lib.cpp file is brought in from the demo and can be changed. You need to write it yourself.
3. CMakeLists.txt File: CMake script configuration file. You need to write your own configuration.

There are also two differences in Gradle:

Java code:

 Public  class mainactivity extends appcompatactivity {    @Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main);//Example of a call to a native methodTextView TV = (TextView) Findviewbyid (R.id.sample_text);    Tv.settext (Stringfromjni ()); }/** * A Native method that's implemented by the ' native-lib ' native library, * which are packaged with this AP     Plication. */     Public nativeStringStringfromjni();//used to load the ' Native-lib ' Library on application startup.    Static{System.loadlibrary ("Native-lib"); }}

From the Native-lib.cpp code we can see that it uses the static registration method, the dynamic registration of the way code with the traditional JNI.

#include <jni.h>#include <string>extern"C"jstringJava_com_example_person_myapplication_MainActivity_stringFromJNI(        JNIEnv* env,        /* this */) {    std::string"Hello from C++";    return env->NewStringUTF(hello.c_str());}

What we need to note in the CMakeLists.txt file is the following three places. The names of the two libraries (which need to be consistent) and the path to a CPP file need to correspond to each other and need to be modified when we define the library ourselves and create the CPP file ourselves.

Run the code, you can see the effect, call the C + + method to display the string on the interface Hello from C++ . This is the cmake way to develop the NDK demo.
Remember the traditional JNI approach? We have used Ndk-build to compile C + + files as so files, for developers who have used third-party libraries, it is certainly not unfamiliar to so. We can only use other people to the so file, and can not see C + + source code, let alone to modify. But here we seem to have not seen the shadow of so file, then, we install running APK, there is a corresponding so file? If you want to verify that the APK has so files, we can use APK Analyzer:

    1. Choose Build > Analyze APK.
    2. Select APK, and click OK.
    3. For example, in the APK Analyzer window, select lib/x86/and you can see libnative-lib.so.

Tips:instant Run is not compatible with projects that use native code. Android Studio will automatically disable the Instant Run feature.

But I am more concerned about the problem is the C + + code automatic completion of the function, when writing code in the CPP file, the inside is no longer a large red, enter a number of letters, you can also give hints, simply diao slag days, as to why ... I don't know why this is a powerful feature here. Which great God can explain ...

CMake compiling so files

Entering CMake in the terminal of Android studio will prompt you to:

‘cmake‘ 不是内部或外部命令,也不是可运行的程序或批处理文件。     

You will need to download the environment variables configured in the CMake, and skip this step if you do not have this problem. Download the corresponding file in the following URL:
https://cmake.org/download/

After you have downloaded the zip package, unzip it. It then adds the path where the Cmake.exe is located to the PATH environment variable. CMake became a valid order.

In the CMakeLists.txt file in the upper directory to execute the cmake . command, error, temporary unresolved:

--Building for:nmake makefiles--The C compiler identification is unknown--The CXX compiler identification is unknownCMake ErrorinchCMakeLists.txt:The CMAKE_C_COMPILER:CL is  notA full path andWas notFoundinch  thePATH. To use theNMake Generator withVisual C + +, CMake must beRun  fromA shell thatcan use theCompiler cl from  theCommand line. This environment isUnable toInvoke theCL compiler. To fix this problem,RunCMake from  theVisual Studio Command Prompt (vcvarsall.bat). Tell CMakewhere  toFind theCompiler bySetting either theenvironment variable"CC" or  theCMake Cache Entry Cmake_c_compiler to  theFullPath to   theCompileror  to  theCompilername if it  is inch  thePATH. CMake ErrorinchCMakeLists.txt:The CMAKE_CXX_COMPILER:CL is  notA full path andWas notFoundinch  thePATH. To use theNMake Generator withVisual C + +, CMake must beRun  fromA shell thatcan use theCompiler cl from  theCommand line. This environment isUnable toInvoke theCL compiler. To fix this problem,RunCMake from  theVisual Studio Command Prompt (vcvarsall.bat). Tell CMakewhere  toFind theCompiler bySetting either theenvironment variable"CXX" or  theCMake Cache Entry Cmake_cxx_compiler to  theFull path to  theCompileror  to  theCompilername if it  is inch  thePATH.--Configuring incomplete, errors occurred!See Also"E:/androiddemo_xy/app/cmakefiles/cmakeoutput.log". See Also"E:/androiddemo_xy/app/cmakefiles/cmakeerror.log".

Pending completion

differences between CMake and traditional JNI on the directory structure and configuration file

Now that we have cmake and traditional JNI two ways to develop the NDK, which differ in the directory structure and the Gradle, we will describe the differences between the directory differences and the Gradle configuration separately.
I. Directory structure
Traditional JNI

CMake

The difference between the two methods in the directory is two points:
1. The previous JNI directory was changed to CPP, the name was changed, and the following is a C/s file.
2. The previous compilation configuration of C + + files Android.mk, application.mk files are placed in the JNI directory and are now converted to CMakeLists.txt files. (In fact, the location of these files can be stored arbitrarily, only need to configure the line.) But it's best to follow the default habits. )

Second, Gradle
Traditional JNI

CMake

In fact, when we use the traditional Jni method, we omit the two places above and do not cause any anomalies (if the ANDROID.MK storage location in other places needs to be configured). The first place in the CMake method can also be omitted, but the second place cannot be omitted (again, the positional path is written to), because no it will not build. Externalnativebuild folder.

In addition, traditional JNI development also needs to be configured in the Gradle.properties file under the project root directory

android.useDeprecatedNdk=true

Otherwise the build project will have an error.

Advantages of CMake
  1. You can directly add breakpoints to the code in C + + to debug
  2. Java refers to the method in C + +, you can directly Ctrl + Left to enter
  3. For include header files or libraries, you can also go directly to the
  4. No need to configure command-line operations, manually generate header files, do not need to configure the Android.usedeprecatedndk=true property
General Android Project to NDK development project

As we said before, when creating a new project, if you tick the Include C++ Support option (requires Android studio version not less than 2.2), then the project is already an NDK development project. So, if the project already exists, how can it be converted to the NDK development project?

Tips: Under the premise of configuring the NDK. And the configuration of the various places are no longer to repeat. such as how to configure in the Android.mk, the configuration in the CMakeLists.txt file, the unification of each place and so on.

The traditional JNI approach, in the NDK development from getting started to giving up (a: basic process primer) We've learned about:

    1. Create a new JNI directory and write the C + + code. Statically registering JNI we used JAVAH-JNI to manipulate the Java class to automatically generate the JNI directory and the corresponding header file (in fact, when we have some experience to write our own, and no longer need to use the Auxiliary command to ensure that the error is not written, and dynamic registration is also a very good way to promote), Then write the C + + code according to the header file. But when we register JNI dynamically we can create the JNI directory by ourselves and write the C + + code as well.
    2. The android.mk and application.mk two files are created and configured in the JNI directory.
    3. The Build.gradle file is configured according to the situation and is not configured to use the default values.
    4. Through the ndk-build operation, we can get the corresponding so file, put it in the corresponding location, Java code can call C + + code, run the program.

Looking back at the previously mentioned CMake approach to NDK development, we get the following steps:

    1. Create a new CPP catalog and write your C + + code.
    2. Create and configure the CMakeLists.txt file.
    3. Build.gradle files are configured as appropriate, the path to the CMakeLists.txt file must be configured.
    4. In Java code, you can call C + + code to run the program.
    5. In Project's Build.gradle file, the Gradle version cannot be less than 2.2, or it will be an error.

Error:could not Find Method Externalnativebuild () for arguments
[Build_e8k5d0w74qu1ajxjrrcr9snog$_run_closure1$[email protected]] on
Project ': App ' of type Org.gradle.api.Project.

NDK development from getting started to giving up (vii: Android Studio 2.2 CMAKE efficient NDK development)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.