Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Arduino: Pass #define to Library (was Configure Library at Compile Time)
#1
If you have a library that you would like to reuse across projects with different hardware or need to support multiple hardware revisions with changing signal pin assignments, you know what this is about. There is several ways I identified so far:

1. library code is entirely in header file

This is frowned upon by C++ programmers as poor coding practice:

project_path/sketch.ino

Code:
#define __MAIN__
#include <mylibrary_config.h>
#include <mylibrary.h>
// ...

project_path/mylibrary_config.h

Code:
#define MY_PIN 2

library_path/mylibrary/mylibrary.h

Code:
#ifndef mylibrary_h__
#define mylibrary_h__ 1
// ... declarations
#ifdef __MAIN__
// ... code using MY_PIN from mylibrary_config.h
#endif // #ifdef __MAIN__
#endif // #ifndef mylibrary_h__


2. extern const

This seems to be preferred method by C++ folks as it does not use preprocessor but C++ features, but I find Arduino does not optimize as well as in case 1 above and produces larger code

project_path/sketch.ino

Code:
#include <mylibrary.h>
extern const int MY_PIN = 2;
//...

library_path/mylibrary/mylibrary.h

Code:
#ifndef mylibrary_h__
#define mylibrary_h__ 1
// ... declarations
extern const int MY_PIN;
#endif // #ifndef mylibrary_h__

library_path/mylibrary/mylibrary.cpp

Code:
#include "mylibrary.h"
// source code using MY_PIN from sketch.ino


3. library configuration header

This seems to be preferred method in embedded development, but Arduino default install does not support it. It is possible by adding -I{build.source.path} in platform.txt before or after {includes}. When used before, the project files may overshadow same-named header files in libraries. I recommend placing it after, so project directory will be searched last.

project_path/sketch.ino

Code:
#include <mylibrary.h>
//...

project_path/mylibrary_config.ino

Code:
#define MY_PIN 2
//...

library_path/mylibrary/mylibrary.h

Code:
#ifndef mylibrary_h__
#define mylibrary_h__ 1
#include <mylibrary_config.h>
// ... declarations
#endif // #ifndef mylibrary_h__

library_path/mylibrary/mylibrary.cpp

Code:
#include "mylibrary.h"
// source code using MY_PIN from mylibrary_config.h
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)