Compilation and debugging of Android native code [go to http://billhoo.blog.51cto.com/2337751/1125039]

Source: Internet
Author: User
Tags gdb debugger
. Http://billhoo.blog.51cto.com/2337751/1125039

I spent two or three days in compiling and debugging environments, and found many tutorials for idea. Bill thought the following tutorials were the most appropriate.

 

Using eclipse for Android-CC Development 

  Using eclipse for Android-CC dubugging 

I followed the tutorial step by step, and there were also some annoying problems during the period. Although I had a great deal of trouble, I finally tasted the sweetness of native code compilation and debugging. It imitates the previous article and records it in step-by-step mode for later use. ---------------------------- Cut line -------------------------------

 

  Step-0 environment preparationThe download and installation of the development and compilation environments have been mentioned on the Internet. Only the environment and version used in this tutorial are listed below for verification. 1) General Android Development Environment (friends who intend to debug native code should already have this environment, and I am using eclipse Juno + ADT-Ver: 21.0.1 + Android SDK + jdk6). The eclipse used in this article has passed the Chinese version. Bill has uploaded the links Chinese package and can be downloaded by anyone who needs it. 2) When installing cygwin 1.7.x cygwin, pay attention to the download of the development kit. The default value is default. We need to select the necessary development kit and expand the devel node to select the following tool kits in sequence, click Next to complete the installation. (3) android-ndk-r8d 4) eclipse Juno CDT plug-in-ver 8.1.1 Step 1 create an android Demo projectCreate a new Android project nativedebugdemo, using Android API 9 (Bill only debugs on api-9 and api-14, other versions are not involved yet ).

Run to make sure that the basic Android environment works properly.

 

Step 2 create and use ndk-build to compile the native code of the project

In eclipse, right-click the project name, create a folder, name it JNI (case sensitive), create a file in the JNI folder, and name it android. MK (case sensitive). Create a file in the JNI directory and name it demo. c

Create a COM. nativetools and create nativedemo class (this class is only used to separate the native code declaration from the general Android code declaration to prepare for the code reuse mentioned in the next article ).

The following code is written to declare the native code to be compiled (the warning can be ignored ):

  1. Package com. nativetools;
  2.  
  3. Public class nativedemo {
  4. Static {
  5. System. loadlibrary ("demomodule"); // load the native code dynamic library libdemomodule. So, which will be explained later
  6. }
  7. Public native int max (int A, int B); // declare the function max as native code. For details, see Oracle JNI Doc.
  8. }

Next we need to write our local code and the Android. mk file, and write the local C code for this demo in demo. C as follows. Pay attention to the name structure of the local function:

Java _

Com_nativetools_nativedemo _

Max

It must start with "Java _" and include the qualified name of the class declared for this function in Android. Here is the previous COM. nativetools. nativedemo (the dots are all replaced by underscores (_), which are case sensitive). The last is the name of the function "Max" (for the local code function name and related specifications, see Oracle jni doc ):

Demo. c

  1. # Include <JNI. h>
  2.  
  3. Jniexport jint jnicall
  4. Java_com_nativetools_nativedemo_max (jnienv * ENV, jobject jthis, jint A, jint B ){
  5. Return A> B? A: B;
  6. }

Next, we need to describe our local code to Android-ndk, and write Android. mk as follows:

Android. mk

  1. Local_path: = $ (call my-DIR)
  2.  
  3. Include $ (clear_vars)
  4.  
  5. Local_module: = demomodule
  6. Local_src_files: = demo. c
  7.  
  8. Include $ (build_shared_library)

For more information about how to write Android. mk files, see local documents/android-ndk-r8d/doc/ANDROID-MK.htlm

The code is ready. Next, you need to configure eclipse to compile the demo.

First, to compile local code in eclipse, You need to convert the current Android project into a hybrid project of Android + C/C ++. Right-click the project name, choose new> other, and select "convert to C/C ++ Project (adds C/C ++ nature )"

In the following dialog box, select this project (selected by default), select "convert to C Project", and select "makefile Project" in the "project type:" box ", select "-- Other toolchain" in "toolchains" on the right and click "finish". In the displayed dialog box, check whether the C/C ++ perspective is opened and select "yes.

Open demo now. c source file, you can see that the CDT has played a role, demo. there are many unrecognized types in C. Next we need to configure C/C ++ and introduce necessary include paths to solve these problems.

Right-click the project name, select "properties", and select "C/C ++ build" in the pop-up property setting box ", remove "use default build command" in "Builder Settings" on the right and modify the "build command" path to the path of your local ndk-build.cmd program, taking Bill himself as an example: "E: \ android_sdk \ android-ndk-r8d \ ndk-build.cmd ", click" application ".

Switch to the behaviour tab, delete the "all" command in the "build (incremental build)" column, and click "application".

Select "C/C ++ General" → "paths and symbols" in the left-side Navigation Pane, select "gnu c" in the "des" column on the right, and click "add".

Click "file system... ", choose Android ndk corresponding platform (this project is the android api-9) include path (in addition to arch-arm inside there are two platforms, This is not needed, For details, please refer to Android-ndk DOC ), take bill as an example: "E: \ android_sdk \ android-ndk-r8d \ platforms \ Android-9 \ arch-Arm \ USR \ include", click "OK", OK and close the Settings dialog box.

Return to demo. C and you can see that all the types that cannot be identified just now can be recognized by CDT. Right-click the project name and click "build project" to complete the compilation process of Android + Local C/C ++.

As you can see, after compilation is successful, a dynamic link library "libdemomodule" is generated under the project/libs/armeabi/directory. so ", name" demomodule "is Bill in androd. (prefix "lib" and suffix "specified in MK ". so "is added by ndk-build, if you are in Android. if MK writes the model name as "libdemomodule", ndk-build will not add the prefix "lib". For details, see Android-ndk DOC) the library loaded in the nativedemo class is "demomodule".

 

Step 3: Call native code in Android

Native code compilation has been completed before. Next we need to call native code in Android to verify whether native code is correct or not.

For the sake of simplicity, Bill directly tests in the oncreate method of mainactivity. The oncreate method is as follows:

  1. ...
  2. Import com. nativetools. nativedemo;
  3.  
  4. Public class mainactivity extends activity {
  5.  
  6. @ Override
  7. Protected void oncreate (bundle savedinstancestate ){
  8. Super. oncreate (savedinstancestate );
  9. Setcontentview (R. layout. activity_main );
  10.  
  11. Nativedemo nativetools = new nativedemo ();
  12. Integer maxnum = nativetools. Max (0, 1); // call the local function max
  13. New alertdialog. Builder (this). setmessage (maxnum. tostring (). Show ();
  14. }
  15. ...

After running the program, we can see that the number "1" is displayed in the pop-up window, and our native code has been successfully run.

 

Step 4 native code debugging

As a developer, Bill believes that debugging takes much longer than development time. As described in this article, we have developed an android test program that calls native code in step 3. However, as long as the program has bugs, debugging is an essential stage, next, Bill explains how to debug native code on Eclipse, which is divided into two parts based on previous practices.

First, use eclipse to debug the Java code, and use ndk-GDB to debug the native code as a command line.

One, merge the two into one, and use eclipse for graphical debugging (this method makes debugging intuitive, but the performance is poor ).

Step 4-1 eclipse + ndk-GDB debug native code

First, we need to set this project as "debuggable". Open "androidmanifest. xml" and set "debuggable" to "true".

In eclipse, the Java code is broken. For simplicity, bill puts the breakpoint at the entrance of native code: Max and starts debugging of the project. The stepping indicator stops at the breakpoint.

Open the cygwin terminal, CD to enter the root directory of the project, execute the ndk-GDB script under the root directory of the android-ndk-r8d, to view the startup process, add the verbose option, enter the command "$ ndk/ndk-GDB -- verbose" (here "$ ndk" is the system environment variable, pointing to the root directory of the android-ndk-r8d, Please configure it yourself), start as follows:

We can see a warning that 48 lib libraries could not be found, including "libstdc ++. So". The ndk official document tells you: please ignore this warning directly ~ (Bill spent a lot of effort at that time to solve this problem, it was fruitless, until you see ndk Doc ......)

Now we are familiar with the "(GDB)". We can list the source code, place a breakpoint on line 1, and then continue, waiting for the android end to enter the native code and trigger the breakpoint.

Next, the eclipse end skips-F6 (or jumps to-F5 in a single step), and the breakpoint on the ndk-GDB side is triggered. We can perform daily debugging:

After the debugging is complete, continue and the process goes back to eclipse. The entire experimental debugging process can be completed.

 

Step 4-2 Use eclipse for unified native code debugging

I have to say that the most cost-effective debugging method at this stage is eclipse + ndk-GDB. Although Java and native code are debugging in two different places, no matter in terms of performance or configuration conciseness, better than the subsequent unified debugging. For this unified debugging method, Bill also learned the configurations of his predecessors and tried to make a record with clear words.

First, copy the "ndk-GDB" script under the android-ndk-r8d root directory to the new file "ndk-GDB-Eclipse", comment out or delete the last line "$ gdbclient-x 'native _ path $ gdbsetup '" (it is best not to open it in notepad, but directly use vs-+ for Bill ),

Go to the \ OBJ \ Local \ armeabi directory of the project and copy the gdb. set "to new file" gdb2.setup ", open" gdb2.setup "and delete" target remote: 5039 ", save and exit.

The Directory should now contain the following files, where "app_progress" and "gdb2.setup" will be used soon. If any of them is missing, please go to cygwin, run "$ ndk/ndk-GDB" in the root directory of this project.

Now that you are ready, go back to eclipse and click the drop-down arrow next to the debug button, select debug configuration, and double-click C/C ++ application. on the "Main" tab on the right, click "select another" at the bottom.

Select overwrite workspace settings and select standard create SS Startup Program.

Confirm to exit, and then fill in the absolute path of app_progress mentioned above in the C/C ++ application column. The bill local settings are as follows:

Click "application", switch to the "Debugger" tab, select "gdbserver" in the "Debugger" column below, and select "Stop on startup: "And fill in our native function name" java_com_nativetools_nativedemo_max "(you can also disable this option and set a breakpoint during debugging)

Next, select the corresponding ndk-GDB version in the "gdb debugger" column, and set "E: \ android_sdk \ android-ndk-r8d \ toolchains \ arm-linux-androideabi-4.6 \ prebuilt \ windows \ bin \ arm-linux-androideabi-gdb.exe ", and then in the" GDB command file: "bar select the" gdb2.setup "we mentioned earlier, check the following two options to interact with GDB on the eclipse console.

Click "application" and switch to the "connection" tab, select "type" as TCP, "port number" as 5039, save and exit.

Now that all preparations are ready, we will start to conduct unified debugging in eclipse. Note the startup steps of each debugging option. Otherwise, the Java breakpoint may not hit, or the native code cannot be debugged. 

First, it looks like you should place a breakpoint in the Java code, start the common debugging option, and wait until the stepping indicator stops at the breakpoint.

In cygwin, run the "ndk-GDB-Eclipse" script in the root directory of the project, that is, the command "$ ndk/ndk-GDB-eclipse-verbose". after successful execution, the gdb interface is not displayed. We will see it in eclipse later ).

After the startup is complete, return to eclipse and click the drop-down arrow next to the debugging button. Select the C/C ++ debugging configuration we configured above. If not, click "Debug configuration". select the one configured above and click "debug".

After the startup is complete, we will see an error:

Don't worry about it. This is caused by the previously mentioned warning. Just ignore it. Now we can see GDB in the eclipse console. You can interact with eclipse here, or directly use visual debugging to go To the demo. in the C source file, double-click a breakpoint to see that the breakpoint information is synchronized to ndk-GDB. In eclipse, you can also skip or skip this step to access native code for daily debugging.

----------------- Cut line ------------------------

Summary

It takes about four days to download, install, and configure the development environment. Now, it is quite simple, but as a newbie, I encountered many problems when I started configuration, fortunately, only by enlightening and helping bloggers write articles on the internet can we build a platform. Therefore, the popularity and importance of technical blogs are evident.

Bill hopes that he can continue to accumulate experience in his future development career, and constantly record and share his learning income with clear words and logic, this is also the most basic mission of a blogger.

Next

In the next article, Bill will briefly introduce how to use the "libnativedemo. So" Dynamic Link Library compiled in this article in another android application.

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.