Question: Is there a way to import .clang-format
code style in Android Studio for native development?
Context:
Hello all,
I am currently working on a cross-platform C++ project, which also involves Android. We have multiple subprojects, including a platform-independent common code base.
The structure of the whole repository looks something like this:
.
├── .idea - Settings for CLion
├── .vscode - Settings for VS Code
├── app
│ ├── android - Full Android project generated by Android Studio
│ │ └── .idea - Settings for Android Studio
│ └── linux - Project for targeting hardware based on Linux
├── core - Platform-independent library with business logic etc.
└── .clang-format - Clang-format configuration file for the whole repository
As you can see, we can use a single .clang-format
file for the whole repository regardless of the used IDE (both CLion and VS Code can be configured by this file). However, I couldn’t find a way to force Android Studio to also use the style defined there. I should mention that the Android project includes native C++ code, which I want to format using the same code style.
I was thinking about multiple ways to achieve this, but none of them worked. I’ve tried:
- Forcing CLion to use
.clang-format
and export IDEA XML settings – does not work, as the settings simply include a directive to enable clang-format support - Find a way to convert
.clang-format
to.editorconfig
, which is supported by AS – couldn’t find any tools for that, and not sure if the two specs overlap enough. - Look for some plugins, custom on save actions etc. – research in progress, nothing so far.
Does anyone have a working solution or some other ideas I may try?
2
Answers
Try to look into File > Settings > Language & Frameworks > C/C++ you will have ability to change if you want use internal android’s studio clang-tidy or external one or clangd.
You can use Android Studio’s External Tools to call the clang-format executable directly on the file you want to format.
It’s not quite as integrated as the built-in formatter (e.g. "undo" will prompt you to reload from disk), but it gets the job done. After you create the tool, you can run it with CTRL+SHIFT+A then type "clang-format" (or w/e you chose to name it). You can also use Android Studio’s Keymap to run the tool.
Either one will format the file currently focused in the editor.
The
-style=file
argument will tell clang-format to look for your.clang-format
file in a parent directory of the file being formatted. The-i
flag will tell clang-format to update the file in line (instead of printing to stdout).$FilePath$
is a substitution variable provided by External Tools and will be replaced by the file currently in focus.