使用Clion优雅开发和调试Android Native C/C++源码
环境:
Windows 11 + wsl2 Ubuntu18.04
Ubuntu下同理
一,Clion安装和注册
1.1 下载clion应用和注册软件
CLion-2023.1.2.tar.gz: 应用可以直接从官方下载
自行解决注册问题,方法同IDEA。
1.2 启动clion
$ tar -zxvf CLion-2023.1.2.tar.gz
$ ./clion-2023.1.2/bin/clion.sh
后台启动
$ nohup ./clion-2023.1.2/bin/clion.sh &
二,Android project导入
2.1 编译生成cmake project
$ source build/envsetup.sh
$ lunch
$ export SOONG_GEN_CMAKEFILES=1
$ export SOONG_GEN_CMAKEFILES_DEBUG=1
$ make nothing
$ mv development/ide/clion/frameworks/native/CMakeLists.txt out/development/ide/clion/frameworks/native/
$ mv out/development/ide/clion/* development/ide/clion/
2.2 open project
clion从{SOURCE}/development/ide/clion/frameworks/native打开项目
x86项目的统一将development/ide/clion/frameworks/native/CMakeLists.txt下arm换成x86_64
修改settings-->Toolchains换成和CMakefiles.txt定义的一致
然后点Reload CMake Project, 无错误说明项目导入成功。
2.3 Change Project Root
点击Tools-->CMake-->Change Project Root改变项目根目录为源码目录{SOURCE}/frameworks/native/
打开代码,可以Find Usages
说明正常使用
三,调试
3.1 clion设置
点击 Run –> Edit configurations, 然后选择Remote Debug, 配置设置为:
Debugger: Bundled GDB
'target remote' arg: :12345 (如果是远程环境需要加上ip, 如ip:12345)
Sysroot: /home/huangqw/code/out/target/product/blueline/symbols
3.2 创建.gdbinit文件
vim ~/.gdbinit
set dir /home/huangqw/code
set solib-absolute-prefix /home/huangqw/code/out/target/product/blueline/symbols
set solib-search-path /home/huangqw/code/out/target/product/blueline/symbols/system/lib64:/home/huangqw/code/out/target/product/blueline/symbols/system/lib64/hw:/home/huangqw/code/out/target/product/blueline/symbols/system/lib64/ssl/engines:/home/huangqw/code/out/target/product/blueline/symbols/system/lib64/drm:/home/huangqw/code/out/target/product/blueline/symbols/system/lib64/egl:/home/huangqw/code/out/target/product/blueline/symbols/system/lib64/soundfx:/home/huangqw/code/out/target/product/blueline/symbols/vendor/lib64:/home/huangqw/code/out/target/product/blueline/symbols/vendor/lib64/hw:/home/huangqw/code/out/target/product/blueline/symbols/vendor/lib64/egl
3.3 adb连接手机
adb root
adb forward tcp:12345 tcp:12345
adb shell
blueline:/ # gdbserver64 :12345 --attach `pidof surfaceflinger`
Attached; pid = 654
gdbserver: Unable to determine the number of hardware watchpoints available.
gdbserver: Unable to determine the number of hardware breakpoints available.
Listening on port 12345
3.4 运行断点调试
回到CLion中,点击Run –> Debug “Unnamed” 开始调试
在截屏代码下打个断点,如SurfaceFlinger::renderScreenImplLocked
然后手动截图,成功断点如上图,接下来就可以单步运行,正常的话可以打开项目外的系统库文件。如图所示堆栈里的Looper函数。如显示的是汇编代码则不正常, 请检查.gdbinit文件,或者在gdb终端里set dir “xxx” 设置源码目录
3.5 变量显示optimized out问题
调试时变量显示optimized out,无法正常查看。这是由于C++编译优化的原因,在Android.bp的cflags里加个”-O0”,重新编译surfaceflinger, push生成即可。