ХабрПостыНовостиМегапосты?

Using kconfig for own projects

Intro


Every Linux professional write scripts. Someеimes light, linear. Sometimes complex script with functions and libs(yes, you can write your bash-library for use in other scripts).


But some of the scripts need a configuration file to work. For instance, I wrote a script that builds the ubuntu image for pxe, and I need to change the build process without build-script changes. The best way to resolve this task is to add configuration files.


Writing this config by hands is not a great idea:



Linux kernel gave us a great solution — KConfig. This system resolves all these troubles:



These are not all the benefits. You can see more here.


How it works


Simplified schema:



After that, you get a ready-made config that can be used in scripts(or for project build).


Example project


Now, I'll show you the demo-project. I placed it on github.


overview


It's a simple script that shows the information about the last logins. Available options:



Just clone this repo and go to its directory:


boozlachu@debian:~$ git clone https://github.com/skif-web/demo-kbuild.git
Cloning into 'demo-kbuild'...
remote: Enumerating objects: 8, done.
remote: Counting objects: 100% (8/8), done.
remote: Compressing objects: 100% (6/6), done.
remote: Total 8 (delta 0), reused 5 (delta 0), pack-reused 0
Unpacking objects: 100% (8/8), done.
boozlachu@debian:~$ cd demo-kbuild/
boozlachu@debian:~/demo-kbuild$ ls
getLast.sh  KConfig  README.md

KConfig interpreter notes


KConfig is just a language. You have to use the interpreter to show the menu. In the Linux kernel, the interpreter is built when you run the "make menuconfig" command. But I'm a lazy potato and will use the kconfig-frontends package. It is available in Debian/Ubuntu, and you can also build it from the source. Or add an interpreter build from source to your project.


KConfig file


The main file here is KConfig. KConfig supports a lot of operators, but I'll use only some of them.


Various types of variables are available there. The most useful are:



boozlachu@debian:~/demo-kbuild$ cat KConfig 
choice SELECT_DESTINATION
    prompt "Select data destination"
    default DESTINATION_TTY

config SELECT_DESTINATION_TTY
    bool "show data in console"
config SELECT_DESTINATION_FILE
    bool "save data to file"
endchoice

config SELECT_DESTINATION_FILE_FILENAME
    string "destination file"
    depends on SELECT_DESTINATION_FILE
    default "last.log"
    help
      Write destination file with relative or full path

config SHOW_ONLY_CURRENT_USER
    bool "show data only for current user"
    default y
    help
      script will get data only for current user

Let's see it. Choice-endchoice pair allows creating SELECT of variants. Inside these keywords, I set definition (prompt), default value (default), and added available variants (SELECT_DESTINATION_TTY, SELECT_DESTINATION_FILE).


The next option (SELECT_DESTINATION_FILE_FILENAME) will only be shown if the destination is the file. The keyword "depends on" allows us to do this. Also, the available keyword "selects" that works in the opposite direction.


Option SHOW_ONLY_CURRENT_USER will always be shown.


Run kconfig in text mode:


boozlachu@debian:~/demo-kbuild$ kconfig-mconf KConfig


And with qt:


boozlachu@debian:~/demo-kbuild$ kconfig-qconf KConfig


Test run


After configuring it, we get .config file with options:


boozlachu@debian:~/demo-kbuild$ cat .config 
#
# Automatically generated file; DO NOT EDIT.
# Configuration
#
CONFIG_SELECT_DESTINATION_TTY=y
# CONFIG_SELECT_DESTINATION_FILE is not set
CONFIG_SHOW_ONLY_CURRENT_USER=y

As you can see, non-selected options are commented on. It's useful for my script.


I run it with this config:


boozlachu@debian:~/demo-kbuild$ ./getLast.sh 
boozlach pts/0        192.168.2.4      Sun Jul 19 06:00   still logged in
boozlach pts/0        192.168.2.4      Sun Jul 19 05:58 - 05:58  (00:00)

wtmp begins Thu Apr 16 05:48:31 2020

I changed the parameters via KConfig and got another result. Now the date was saved to a file, instead of being shown in the console:


boozlachu@debian:~/demo-kbuild$ cat .config
#
# Automatically generated file; DO NOT EDIT.
# Configuration
#
# CONFIG_SELECT_DESTINATION_TTY is not set
CONFIG_SELECT_DESTINATION_FILE=y
CONFIG_SELECT_DESTINATION_FILE_FILENAME="last.log"
CONFIG_SHOW_ONLY_CURRENT_USER=y
boozlachu@debian:~/demo-kbuild$ ./getLast.sh 
boozlachu@debian:~/demo-kbuild$ cat last.log 
boozlach pts/0        192.168.2.4      Sun Jul 19 06:00   still logged in
boozlach pts/0        192.168.2.4      Sun Jul 19 05:58 - 05:58  (00:00)

Conclusion


As you can see, KConfig is very powerful and friendly util for configuring. It can be used for scripts, package building, and other variants.


If you want to see an improved variant of KConfig using a makefile in the real project — write in comments.

@Boozlachu
17.08.2020 12:01 UTC
Первоисточник

Комментарии

@edo1h
18.08.2020 04:29 UTC
0
for example, kconfig-frontends project

Какие есть альтернативы?


Ситуация с фрагментацией KConfig какая-то нездоровая: buildroot тащит свой чуть патченный, busybox — свой, отпочковавшийся ещё до появления make nconfig. И, думаю, так с каждым проектом.

17.10.2022 20:29 UTC
0

Так и есть. Вы правы @edo1h. В пресловутом Zephyr project и вовсе своя собственная внеочередная реализация утилиты Kconfig, причем на остове python скриптов.

@aabzel
17.10.2022 20:27 UTC
0

Как через механизм Kconfig передать в код макро-определение произвольного имени? Например HAS_XXX.

То есть не CONFIG_XXX, а именно HAS_XXX?

How to define in Kconfig a macro definition of specific name?

@anti_smithhh
25.02.2023 20:48 UTC
0

стал осваивать данную тулзу с целью прикрутить к своим мини-недо-проектам и обнаружил, что, например, наличие tristate в файлах ‘kconfig’ не вызывает ошибок при открытии утилитой kconfig-mconf например, но активизировать ‘третье состояние’ никак невозможно.. опция ‘modules’ тупо вызывает ошибку - не поддерживается парсером.

Стал штудировать kernel.org - обнаружил, что там ещё переменные и другие фичи есть. Но всё это не работает!

А вот парсер, идущий с сырцами ядра, - ./scripts/kconfig/mconf, всё умеет.

Никакие apt-update и тд не помогали. Все варианты не умели в ‘третье состояние’ и переменные.

РЕШЕНИЕ: из сырцов ядра просто заменил в системе пару бинарников:

1) ./scripts/kconfig/mconf -> /bin/kconfig-mconf

2) ./scripts/kconfig/conf -> /bin/kconfig-conf

всё стало работать так, как описано в документации.

Но осадок остался. Должно же работать ‘из коробки’ по идее ?‍♂️ Как надо было бы нормально решать эту проблему?

@DungeonLords
31.05.2023 12:29 UTC
0

На этом этапе демо-примера ошибка
путь/demo-kbuild$ kconfig-mconf KConfig
bash: kconfig-mconf: command not found

На Ubuntu решилось так
sudo apt-get install kconfig-frontends

@aabzel
16.01.2024 15:18 UTC
0

Существует ли standalone Kconfig для использования в произвольных проектах на Windows?