valuechange event similar functionality in c or c++ - c++

I'm implementing a global debug module ,a single module contains a struct to hold all global variables in C, and our code has both C and C++ modules. Is there a way if an existing variable is set somewhere, would also cause to update debug global variables in structure as well.
I was thinking of setter functions , but this requires modification in every module.Instead is there a way to replicate functionality like valuechangeevent in JSF with C or C++.

You can make the debug module contains all the pointers to the variables you are monitoring.
struct debug {
int * pointer_to_var_1;
};
struct debug __debug__;
__debug__.pointer_to_var_1 = &var_1;
Now suppose var_1 is changed somewhere, and you can directly see from __debug__ by accessing:
*(__debug__.pointer_to_var_1) //This is up to date
Otherwise, you will have to use a setter and change everything in the modules, or use an infinite loop or timer to monitor all the variables. There is no event registration for value change in C.

You might be able to do it with some pre-processor trickery:
#ifdef DEBUG
#define myvar global_debug_thingy->myvar
#else
int myvar;
#endif
I don't think that you can do accessor functions, or notifiers this way as it would need different code for reading and writing, and preprocessor can't do this.

Related

C++ Compile time check if a microcontroller pin is already initialized from other source file

Typically a microcontroller pin can be identified with with port number and pin number.Both are compile time constants.
A pin can have multiple functions,if used in a big project multiple source file can initialize same pin and break functionality implemented in other module.
I want to implement a compile time list which is initially empty and each time a pin is initialized it will check if the pin is already
present in that list, if its present it will give a static assert otherwise it will insert pin information in the list. List is not required at run time.
I don't have enough knowledge of meta programming, It would be great if someone can provide me direction to implement it.If there is already some library for this kind of purpose, please provide the links
What you want is not possible. C++ metaprogramming does not have a state, it's more akin to a functional language than declarative one. So you cannot have a mutable list. The only state can be introduced by creating new types, but there's no available syntax to check if a particular non-nested name is declared or defined.
Multiple source files (compilation units) are compiled independently so there's certainly no "global state" and that makes it more impossible.
Also, note that what you are doing is inherently run-time. The compiler has no tools to check if you are calling the initialization function twice. These calls might be hidden behind some run-time if-else decisions. And simply writing HAL_GPIO_Init(); no matter how many times in the whole program is not an error.
The simplest thing I can think of is creating a C++ singleton class that is responsible for communicating with pins. You can have a dedicated int init_GPIO method using error_codes or exceptions if they are enabled. Instead of static_assert you will have to rely on tests - that singleton works correctly and the return value of init_GPIO is not ignored.
If you really do not want to bother with singleton, this function template works too:
template<std::size_t GPIO, std::size_t port> int GPIO_init(GPIO_InitStruct& s){
static bool initialized=false;
if(initialized) return <already_called>;
initialized=true;
//Assuming that you want to propagate the return value.
return HAL_GPIO_Init(GPIO, port, s);// Replace with the correct call.
}
If you require thread-safe initialization then use:
template<std::size_t GPIO, std::size_t port> int GPIO_init(GPIO_InitStruct& s){
static std::once_flag initialized;
int ret_val = <already_called>;
auto call = [&](){ret_val = HAL_GPIO_Init(GPIO, port, s)};
std::call_once(initialized, call);
return ret_val;
}
Assuming that every driver or HAL has a header file, and there's a main.cpp which includes all those headers, then you can do this with the pre-processor.
Optionally, make a project-wide header "pintype.h" with an enum such as this:
// pintype.h
typedef enum
{
PIN_GPIO,
PIN_PWM,
PIN_ADC,
PIN_UART,
...
} pin_t;
Then for every header file, write a pre-processor check, for example:
// pwm.h, header of the pwm driver or HAL
#include "pintype.h"
#ifdef PIN9
#error Pin 9 already taken
#else
#define PIN9 PIN_PWM
#endif
The #error is strictly speaking not needed, because in case of conflicts the compiler will complain about multiple definitions in the same translation unit (that of main.cpp).
When the developer writing the driver gets an error message, they can go to the pre-processor definition of the pin and find out which other module in the project that has claimed it already, without digging inside the internal implementation of that driver.

How do I use ConditionalAttribute in C++-CLI?

I have a C++-CLI ref class that exposes a profiling infrastructure implemented in C++.
In C++ I have the preprocessor directive PROFILING_ENABLED to determine whether the intrusive profiling functions are in the code or not.
When exposing these to managed code, I thought that using the managed ConditionalAttribute would be appropriate. But I struggle with the syntax.
Here is my attempt:
#ifdef PROFILING_ENABLED
// c++ macros are defined and active on the project level, I would like the
// conditional attribute to be active as well.
#define MANAGED_PROFILING_ENABLED
// how do I define the managed conditional "MANAGED_PROFILING_ENABLED" in C++-CLI?
#endif
public ref class Profiler
{
public:
[ConditionalAttribute("MANAGED_PROFILING_ENABLED")] // this compile but always inactive
static void PushRange(System::String ^ name, Color color);
[ConditionalAttribute("MANAGED_PROFILING_ENABLED")]
static void PopRange();
};
I would like to achieve the following:
If the native c++ preprocessor directive is active, the managed ConditionalAttribute should be active as well.
If on the other hand the native c++ preprocessor directive is inactive, the managed ConditionalAttribute should be inactive.
The below standards document is pretty old. But assume that, may be still valid.
https://www.ecma-international.org/publications/files/ECMA-ST/ECMA-372.pdf
Go to section 29.4.3 (You can find below content about conditional attributes in c++/CLI).
C++/CLI does not provide this ability; although attributes of this
type are accepted, they have no affect on code generation or
execution.

Arduino - How to write Macro that define used pins by name and number and throw compiler error if pin is used elsewhere

I have been playing with this for the last 2 hours now. It should be simple but it does not work. I am not really familiar with macros and I never used them really because of their known instability. But in this case... I don't see any other better way to not use any chip memory.
What I want is not to use memory on chip for this so I choose precompiler directives, especially macros. The macro just have to define stuff, not return anything. I want that macro to be equivalent to this code :
#define PIN3 = 13;
#define PINLED = 13;
And it should be called like that :
P(13,LED);
So that way I can reference PINLED in my code and get a compiler error if any other library or code I use happens to use PIN13 when I put the P(13,LED) in the top of all the files that uses this pin in my project. I want something that names all pins the same way.
I want the 2 constants/defines to be "defined" so PIN13 cause a compiler error, but PINLED might be named different in many projects
I have tried this :
#define P(no_,name_) \
if (true) { \
PIN##name_ = no_; \
PIN##no_ = no_; \
}\
else true
This works but does only 1 define instead of 2 :
#define P(no_,name_) PIN##name_ = no_
This was suggested by many as the correct syntax. I also tried with the do... while(0) syntax and other tricks so I can use the macro as a function with a ; after it but is does not work and always throws some error.
I am using the Ino project to build because I cannot live with the arduino IDE which is pure crap compared to other IDEs.
Sorry, but your question is hardly understandable. You say you want to check whether a pin has already been used in another part of the project, and in the same time you're showing code for defining macros in macros.
But that's where it hurts, like #graben showed, it's simply not possible to achieve in C. First of all both of your syntaxes are wrong:
#define P(no_,name_) PIN##name_ = no_
you're not creating a macro name PINLED to which you assign 13, but you're assigning to the C variable PINLED the value 13. To make your PIN definition macro work, you'll need to use const int variables, which usually are easily optimized by the compiler.
Now, to get to the goal you say you want to achieve, I think it's very unlikely you can do it in macro processor code, at least in an elegant way...
And I don't think that's even necessary!
If you design well your libraries, you should not be using the pin number throughout your code and libraries, but design them so you define pins for each library at the library initialization stage. That's why usually Arduino libraries work in three steps:
allocate the memory (which is done by calling the constructor, which is often made in the included header file as a global object) ;
configure the instance (which is done with the .begin() method)
use the instance
so basically, if you have all your pins defined in the same file, you should not run into pin reuse elsewhere in your code.

Strange #define in Template?

I've got a small bit of code from a library that does this:
#define VMMLIB_ALIGN( var ) var
template< size_t M, typename T = float >
class vector
{
...
private:
// storage
VMMLIB_ALIGN( T array[ M ] );
};
And you can call it by doing
//(vector<float> myVector)
myVector.array;
No parenthesis or anything.
what?
After reading the answers, it appears I should've done more looking. XCode's "Jump to Definition" gave me only one result. Searching the library gave me another:
#ifndef VMMLIB_CUSTOM_CONFIG
# ifndef NDEBUG
# define VMMLIB_SAFE_ACCESSORS
# endif
# define VMMLIB_THROW_EXCEPTIONS
# ifdef VMMLIB_DONT_FORCE_ALIGNMENT
# define VMMLIB_ALIGN( var ) var
# else
# ifdef __GNUC__
# define VMMLIB_ALIGN( var ) var __attribute__((aligned(16)))
# elif defined WIN32
# define VMMLIB_ALIGN( var ) __declspec (align (16)) var
# else
# error "Alignment macro undefined"
# endif
# endif
#endif
This offers different settings, depending on what system it's building for.
Regardless, thanks. Can't believe I got confused over a member access!
Ultimately, myVector.array refers to the array variable in the class, and variables don't need the function-calling notation ().
BTW / all-capital identifiers should only be used for preprocessor macros (as they are here). In this case, the macro VMMLIB_ALIGN must be being used to make it easier to later "enchance" the code generated for and alongside the array variable (e.g. prefixing it with static, extern, const, volatile or something compiler-specific) and/or adding some associated functionality such as get/set/search/clear/serialise functions that work on the array.
In general - when you're not sure what the macro is doing, you can get more insight by running the compiler with a command-line switch requesting preprocessor output (in GNU g++, the switch is -E)... then you'll be able to see the actual source code that the C++ compiler proper deals with.
EDIT - few thoughts re your comment, but too long to include in a comment of my own...
C++ classes are private until another access specifier is provided (but in practice the public interface is normally put first so the programmer still must remember to explicitly use private). structs are public by default. So, data is effectively exposed by default in the most common coding style. And, it doesn't need functional-call semantics to access it. Objective-C may well be better at this... your comment implies you use functional call notation for data members and functions, which is hidden by default? It's so good to have a common notation! In C++, the difficult case is where you have something like...
struct Point
{
double x, y;
};
...
// client usage:
this_point.x += 3 - that_point.y;
...then want to change to...
struct Point
{
double angle, distance;
};
...you'd need some pretty fancy and verbose manually-coded and not terribly efficient proxy objects x and y to allow the old client code to keep working unmodified while calculating x and y on the fly, and updating angle and distance as necessary. A unified notation is wonderful - allowing implementation to vary without changes to client source code (though clients would need to recompile).
maybe I'm oversimplying, but if you look at the #define macro it just writes the variable into the class.
So you have
class vector
{
...
T array[ M ];
};
after the expansion. So it's just a public variable on your class.
array is not a method, it's an array of type T of size M.
First, for the record, templates have nothing to do with this. There is no special interaction between the macro and the fact that your class is a template.
Second, going by the name of the macro, I'd guess it is meant to ensure alignment of a variable.
That is, to get an aligned instance x of a type X, you'd use VMMLIB_ALIGN(X x);
In practice, the macro does nothing at all. It simply inserts its argument, so the above results in the code X x; and nothing else.
However, it may be that the macro is defined differently depending on the hardware platform (since alignment requirements may vary between platforms), or over time (use a dummy placeholder implementation like this early on, and then replace it with the "real" implementation later)
However, it does seem pointless since the compiler already ensures natural alignment for all variables.

C++ Preprocessor metaprogramming: obtaining an unique value?

I'm exploiting the behavior of the constructors of C++ global variables to run code at startup in a simple manner. It's a very easy concept but a little difficult to explain so let me just paste the code:
struct _LuaVariableRegistration
{
template<class T>
_LuaVariableRegistration(const char* lua_name, const T& c_name) {
/* ... This code will be ran at startup; it temporarily saves lua_name and c_name in a std::map and when Lua is loaded it will register all temporarily global variables in Lua. */
}
};
However manually instantiating that super ugly class every time one wants to register a Lua global variable is cumbersome; that's why I created the following macro:
#define LUA_GLOBAL(lua_name, c_name) static Snow::_LuaVariableRegistration _____LuaGlobal ## c_name (lua_name, c_name);
So all you have to do is put that in the global scope of a cpp file and everything works perfectly:
LUA_GLOBAL("LuaIsCool", true);
There you go! Now in Lua LuaIsCool will be a variable initialized to true!
But, here is the problem:
LUA_GLOBAL("ACCESS_NONE", Access::None);
Which becomes:
static Snow::_LuaVariableRegistration _____LuaGlobalAccess::None ("ACCESS_NONE", &Access::None);
:((
I need to concatenate c_name in the macro or it will complain about two variables with the same name; I tried replacing it with __LINE__ but it actually becomes _____LuaGlobalAccess__LINE__ (ie it doesn't get replaced).
So, is there a way to somehow obtain an unique string, or any other workaround?
PS: Yes I know names that begin with _ are reserved; I use them anyway for purposes like this being careful to pick names that the standard library is extremely unlikely to ever use. Additionally they are in a namespace.
You need to add an extra layer of macros to make the preprocessor do the right thing:
#define TOKENPASTE(x, y) x ## y
#define TOKENPASTE2(x, y) TOKENPASTE(x, y)
#define LUA_GLOBAL(lua_name, c_name) ... TOKENPASTE2(_luaGlobal, __LINE__) ...
Some compilers also support the __COUNTER__ macro, which expands to a new, unique integer every time it is evaluated, so you can use that in place of __LINE__ to generate unique identifiers. I'm not sure if it's valid ISO C, although gcc accepts its use with the -ansi -pedantic options.