Force one include file to be included before another - c++

Imagine I have two .hpp files:
#ifndef _DEF_FILE_1_
#define _DEF_FILE_1_
inline void some_function_1(){
/*do stuff*/
}
#endif
and
#ifndef _DEF_FILE_2_
#define _DEF_FILE_2_
#ifdef _DEF_FILE_1_
inline void some_function_2(){
/*do stuff using some_function_1()*/
}
#else
inline void some_function_2(){
/*do the same stuff without using some_function_1()*/
}
#endif
#endif
My problem arises when I don't know in which order the files are included, e.g:
in the main.cpp i can have something like :
#include "file1.hpp"
#include "file2.hpp"
int main(){
some_function_2();
/*will call the function that uses some_function_1()*/
}
or
#include "file2.hpp"
#include "file1.hpp"
int main(){
some_function_2();
/*will call the function that doesn't use some_function_1()*/
}
Is there a way to make sure that as soon as both file1.hpp and file2.hpp
are included, then some_function_2() will call some_function_1()?
PS: One solution would be to include file1.hpp in file2.hpp but I can't do
that because I developp a code that may or may not depend on some library
that the end-user may or may not have.
PPS: The only other solution I can think of (even if I don't know how to
achieve this) would be to "delete" the definition of some_method_2() when
file1.hpp is included and then reinclude file2.hpp.

I believe proper solution would be to rewrite some_function_2() using SFINAE mechanism and template instead of preprocessor tricks. That way instantiation will happen in cpp file where it would be known if some_function_1() exists and order of include will not matter.

Your users should know if they have "some library" or, you should have some way of determining if that library is present. So you could do something like:
In file2.hpp
#ifndef _DEF_FILE_2_
#define _DEF_FILE_2_
#ifdef _DEF_HAS_SOME_LIBRARY_
#include "file1.hpp"
inline void some_function_2(){
/*do stuff using some_function_1()*/
}
#else
inline void some_function_2(){
/*do the same stuff without using some_function_1()*/
}
#endif
#endif
Or if possible eliminate file1.hpp entirely, and put some_function_1() in the location of #include "file1.hpp" above.
Now main.cpp should only include file2.hpp.
// optionally #define _DEF_HAS_SOME_LIBRARY_
#include "file2.hpp"
int main(){
some_function_2();
/*will call the function that uses some_function_1()*/
}
though, a solution that avoids the preprocessor would be better in my opinion.

If you don't know whether the file exists and need to handle that, well, neither c nor c++ preprocessor handle file existence checks. This is one of the reasons behind configure tools.
You need to probe for this information beforehand, and set it before compiling. There many ways to do it. Usually a tool / script, creates some configure.h header with appropriate defines is created. E.g. containing such line #define FILE1_HPP_EXISTS 1.
Then you can always rely on presence of configure.h and it will provide information you need.

If your compiler allows it you might use the _has_include macro:
Just change you file2.hpp to:
#ifndef _DEF_FILE_2_
#define _DEF_FILE_2_
#if defined(__has_include) && __has_include("file1.hpp")
# include "file1.hpp"
inline void some_function_2() {
/*do stuff using some_function_1()*/
}
#else
inline void some_function_2() {
/*do the same stuff without using some_function_1()*/
}
#endif
#endif
But keep in mind that this is a compiler specific extension.

Related

how to include a separate file containing functions for a class

So i am making a library for a hardware to be used with arduino. Inside that class there are some hardware specific code that needs to included. To improve readability i would like to move the hardware specific functions to another file
//.h
class myClass(){
public:
myClass();
void controlGPIO();
};
//.cpp
myClass::myClass(){
controlGPIO();
}
#ifdef HARDWAREA
#include "deviceA_hal.h"
#endif
#ifdef HARDWAREB
#include "deviceB_hal.h"
#endif
//deviceA_hal.h HardwareA functions
#include <deviceA_specific_Library>
void myClass::controlGPIO(){
// some code unique to hardwareA
}
//deviceB_hal.h HardwareB functions
#include <deviceB_specific_Library>
void myClass::controlGPIO(){
// some code unique to hardwareB
}
Is this possible ? Am i doing this correctly?
This would make adding more specific hardware easier and cleaner. Is there a more better way of doing it>?
Common is to do one .cpp with
#if defined(HARDWAREA)
#include "deviceA_hal.h"
#elif defined(HARDWAREB)
#include "deviceB_hal.h"
#endif
void myClass::controlGPIO(){
#if defined(HARDWAREA)
// some code unique to hardwareA
#elif defined(HARDWAREB)
// some code unique to hardwareB
#endif
}
this is simpler to maintain than two separate files

#define c-preprocessor constants ... what did I wrong?

I am trying once more with arduino and create a small module just to gain fluency in the cpp sintaxe.
I am trying to create a utility module with a static method and using a header constant to decide if I have to print the debug messages or not.
But even using #ifndef to avoid duplications, I did not work
In the module DataMattersUtil I set the header constant DATA_MATTERS_DEBUG to false using #ifndef to avoid duplication. But when I execute this code, the message does not print on serial monitor because the constant is always false, even setting it to true on the module DataMattersRunner.ino that is the first to execute.
File: DataMattersRunner.ino
#define DATA_MATTERS_DEBUG true
#include <DataMattersRunner.h>
DataMattersRunner runner;
void setup() {
runner.setup();
}
void loop() { }
File: DataMattersRunner.cpp
#include <DataMattersUtil.h>
void DataMattersRunner::setup() {
DataMattersUtil::debug("Running ...");
}
File: DataMattersRunner.cpp
#include <DataMattersUtil.h>
void DataMattersRunner::setup() {
DataMattersUtil::debug("Running ...");
}
File: DataMattersUtil.h
#ifndef DATA_MATTERS_DEBUG
#define DATA_MATTERS_DEBUG false
#endif
#ifndef DataMattersUtil_h
#define DataMattersUtil_h
class DataMattersUtil {
public:
static void debug(String message);
};
void DataMattersUtil::debug(String message) {
if(DATA_MATTERS_DEBUG) {
Serial.println(message);
}
}
#endif
As DataMattersUtil.h is included in multiple compilation units you have to define DATA_MATTERS_DEBUG in all of them.
Instead of adding #define DATA_MATTERS_DEBUG before all #include <DataMattersUtil.h> you would use a compiler flag to do so. For gcc and clang it would be -DDATA_MATTERS_DEBUG
Your problem is that each cpp file is handled in a different compilation unit, and you've only defined DATA_MATTERS_DEBUG to true in DataMattersRunner.ino. Because your other files are in separate compilation units, they don't see the definition in DataMattersRunner.ino.
The best solution for you is probably to provide DATA_MATTERS_DEBUG using a compiler option. I don't have Arduino experience, but with gcc you can do something like this:
g++ -c DataMattersRunner.cpp -DDATA_MATTERS_DEBUG=true

How to override "default" #define values ​of a C ++ library header with new values ​defined in an application header

What I'm trying to do is provide a library with some defaults set by #define directives in the library header. Those would determine what functions of the library code will be compiled with a given application. In case the application developer needs to add or remove library functions, it should "override" the library's defaults ​​with new values ​​without modifying the library. Besides modifying the library compiled code, those application header's #define values will, in turn, add or remove parts of the application code itself. This is for an embedded system, so even small memory savings are important.
Below are the 4 test files. I can't get it working if it's even possible to do this. Maybe the right question is: What's the correct order of #define / #undef inside the project files?
library.h:
#ifndef MY_LIBRARY_H
#define MY_LIBRARY_H
#include <stdio.h>
#define FUNCTION_1 true
#define FUNCTION_2 false
class Class {
public:
Class();
~Class();
#if FUNCTION_1
void Function_1(void);
#endif
#if FUNCTION_2
void Function_2(void);
#endif
};
#endif // MY_LIBRARY_H
library.cpp:
#include "library.h"
Class::Class() { /* Constructor */ };
Class::~Class() { /* Destructor */ };
#if FUNCTION_1
void Class::Function_1(void) {
printf("Hi, this is %s running ...\n\r", __func__);
}
#endif
#if FUNCTION_2
void Class::Function_2(void) {
printf("Hi, this is %s running ...\n\r", __func__);
}
#endif
tst-09.h
#ifndef TST_09_H
#define TST_09_H
#include <library.h>
#undef FUNCTION_2 // .....................................................
#define FUNCTION_2 true // THIS IS WHERE I'M TRYING TO OVERRIDE THE LIB DEFAULTS
#endif // TST_09_H
tst-09.cpp:
#include "tst-09.h"
int main(void) {
Class object;
#if FUNCTION_1
object.Function_1();
#endif
#if FUNCTION_2
object.Function_2();
#endif
}
Take advantage of the capabilities of your linker. If you want to exclude unused or unnecessary code from you binary, one way to do that is to put each function in its own source module. (Some compiler packages support Function Level Linking, where the linker can remove unreferenced functions.)
Trying to use macros the way you show in your question would need them to be defined on the command line (and the library rebuilt with any change).

C++ Macro define and undefine

I want to use macros to quickly create inlined functions in headers, these functions are related to a base class which I am subclassing. I'll put the definitions inside the base class header but I do not want to pollute everything that include these headers with all macro definitions, so I would like to write something like this (which unfortunately doesn't work):
#define BEGIN_MACROS \
#define MACRO_1(...) ...\
#define MACRO_2(...) ...\
#define MACRO_3(...) ...
#define END_MACROS \
#undef MACRO_1\
#undef MACRO_2\
#undef MACRO_3
And then use it like:
BEGIN_MACROS
MACRO_1(...)
MACRO_2(...)
MACRO_3(...)
END_MACROS
perhaps should I use something like this?
#include "definemacros.h"
MACRO_1(...)
MACRO_2(...)
MACRO_3(...)
#include "undefmacros.h"
And put definitions and "undefinitions" in two separate headers...
Or is there a better approach overall to overcome this kind of problems?
Or do you suggest to avoid at all the use of macros and/or macros in headers?
Edited to include specific use case:
definition:
#define GET_SET_FIELD_VALUE_INT(camelcased, underscored)\
inline int rget ## camelcased () { return this->getFieldValue( #underscored ).toInt(); }\
inline void rset ## camelcased (int value) { this->setFieldValue( #underscored , value); }
use:
class PaymentRecord : public RecObj
{
public:
GET_SET_FIELD_VALUE_INT(PriceIndex, price_index)
//produces this
inline int rgetPriceIndex() { return this->getFieldValue("price_index").toInt(); }
inline void rsetPriceIndex(int value) { this->setFieldValue("price_index", value); }
};
you can not stack up more defines into single line (at least to my knowledge... What I would try to do is encapsulate those into 2 separate files instead like this:
file macro_beg.h:
#define MACRO_1(...) ...
#define MACRO_2(...) ...
#define MACRO_3(...) ...
file macro_end.h:
#undef MACRO_1
#undef MACRO_2
#undef MACRO_3
It just like your second case but the macros are not in single line ...
#include "macro_beg.h"
MACRO_1(...);
MACRO_2(...);
MACRO_3(...);
#include "macro_end.h"
But as Some programmer dude commented this might not work properly or at all depending on the compiler preprocessor and macro complexity or nesting with class/template code. For simple stuff however this should work.

Referencing C functions in static library from C++

I have a static library of functions written in C. Let's say the header file is called myHeader.h and looks like:
#ifndef MYHEADER_H
#define MYHEADER_H
void function1();
void function2();
#endif
function1 and function2 aren't anything too special. Let's say they exist in a file called impl1.c which looks like:
#include "myHeader.h"
void function1() {
// code
}
void function2() {
// more code
}
All of the code mentioned so far is compiled into some static library called libMyLib.a. I'd rather not modify any of the code used to build this library. I also have a C++ header (cppHeader.h) that looks like:
#ifndef CPPHEADER_H
#define CPPHEADER_H
class CppClass {
private:
double attr1;
public:
void function3();
};
#endif
Then cppHeader.cpp looks like:
#include "cppHeader.h"
#include "myHeader.h"
// constructor
CppClass::CppClass(){}
void CppClass::function3() {
function1();
}
When I try to compile this, I get an error about an undefined reference to function1(). I believe that I've linked everything properly when compiling. I'm pretty rusty in my C++. I'm sure that I'm just doing something stupid. I hope that my simple example code illustrates the problem well enough.
Thanks in advance for any help!
The other solution (to the one suggested originally by Yann) is to surround your "C" header with:
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __cplusplus
}
#endif
Which saves you from having to remember to do:
extern "C" {
#include "foo.h"
}
every place you use foo.h
Make sure to use:
extern "C" {
#include "myHeader.h"
}
Or else the C++ compiler will generate symbol names which are name-mangled.