2

Considering a small embedded C project, how to decide if certain constants belong to

  • a global configuration file
  • the header of the "module == compilation unit"
  • on top of the the actual C file
  • or inside the code?

    I am talking about constants that can often change, and need to be conveniently located for the end user, as well as for the developer. Several examples include ENABLE_GLOBAL_ERROR_CHECKING, USART_BAUD_RATE and TEMPERATURE_SETPOINT.

  • 3
    I'm irritated by the phrase “constants that can often change”. Can you explain this? – 5gon12eder Jan 12 '16 at 22:29
  • 1
    <g> It happens. If you are in the phase of tweaking the system to an optimum. Once it is delivered the values could be constant from a user perspective. – Martin Maat Jan 13 '16 at 6:50
3

If the user should be able to change the values, putting them in the code as constants is obviously not an option. A text file with key-value pairs seems appropriate (concidering it is for a small project).

In general you should ask yourself if you want to tie your settings to a group of users, the machine, the program file or the individual user. You may want to combine them too, having user settings override machine- or group settings.

Or you may accept a settings file path as an argument to your program so you can keep multiple configurations that may be activated on a per run basis.

  • I see you added the word "embedded" to your question. This renders part of my answer useless, I was thinking of a program that was started interactively, possibly by different people. – Martin Maat Jan 13 '16 at 6:56
  • Sorry. Even after this edit, my question is still not quite what I have in mind. Have a +1 as a compensation :) – Vorac Jan 13 '16 at 19:17
2

For embedded programming, it is usually preferable to have the constants at the top of the source file. This is to ensure readability and ease to change the value quickly without having to delve into the code and modify them.

#include <thisLibrary.h>
#include <thisOtherLibrary.h>

#define USART_BAUD_RATE 10000
#define SOME_OTHER_VALUE 1234

For other purposes, use files like XML and JSON to save the data. Of course, special libraries will be required to read these into your program.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.