redefining a macro not working as expected - c++

I am in C++ defining blocks that go in a special area of memory. I want to define a block, then define the address of the next block in a variable that gets redefined for each block.
#include <iostream>
using namespace std;
#define BASE_ADDRESS 0X1000
// type a gets 100 bytes
#define TYPE_A BASE_ADDRESS
#define NEXT_FREE_BLOCK (BASE_ADDRESS + 100)
// type b gets 200 bytes, starting at the next free address
#define TYPE_B NEXT_FREE_BLOCK
#undef NEXT_FREE_BLOCK
#define NEXT_FREE_BLOCK (TYPE_B + 200)
// ---end of RWW memory map---
int main()
{
cout<<"Hello free block " << NEXT_FREE_BLOCK << endl;
return 0;
}
Example code that I've looked up looks like this. But when I try to compile this, I get "compilation failed due to the following errors":
main.cpp:12:16: error: ‘NEXT_FREE_BLOCK’ was not declared in this scope
#define TYPE_B NEXT_FREE_BLOCK
^
main.cpp:14:26: note: in expansion of macro ‘TYPE_B’
#define NEXT_FREE_BLOCK (TYPE_B + 200)
^~~~~~
main.cpp:20:34: note: in expansion of macro ‘NEXT_FREE_BLOCK’
cout<<"Hello free block " << NEXT_FREE_BLOCK << endl;
^~~~~~~~~~~~~~~
If I comment out the 'type b' lines, it runs as expected. If I comment out the #undef line, it tells me I've redefined the macro. I would like to redefine the macro without getting an error or warning; is there a way to do that?

Lets take a look at this example:
#define MYMACRO 0 //MYMACRO = 0
#define ANOTHERMACRO MYMACRO //ANOTHERMACRO = MYMACRO = 0
int main() {
return ANOTHERMACRO;
}
All good right?
But if we do this:
#define MYRECURSIVEMACRO 0 //MYRECURSIVEMACRO = 0
#define MYMACRO MYRECURSIVEMACRO //MYMACRO = MYRECURSIVEMACRO
#undef MYRECURSIVEMACRO // MYRECURSIVEMACRO does not exist
#define MYRECURSIVEMACRO (MYMACRO+10) //What was MYMACRO again? It was MYRECURSIVEMACRO, but now we are setting MYRECURSIVEMACRO, which right now is being defined, to itself plus 10, and now I am 100% confused
#define ANOTHERMACRO MYRECURSIVEMACRO //Now what?
int main() {
return ANOTHERMACRO;
}
We get this:
1>C:\dev\Stack Overflow\Source.cpp(520,9): error C2065: 'MYMACRO': undeclared identifier
(At least for MSVC++)
Now if we look at this:
#define BASE_ADDRESS 0X1000 //BASE_ADDRESS = 0x1000
// type a gets 100 bytes
#define TYPE_A BASE_ADDRESS //TYPE_A = BASE_ADDRESS = 0x1000
#define NEXT_FREE_BLOCK (BASE_ADDRESS + 100) //NEXT_FREE_BLOCK = 0x1000 + 100
// type b gets 200 bytes, starting at the next free address
#define TYPE_B NEXT_FREE_BLOCK //TYPE_B = NEXT_FREE_BLOCK
#undef NEXT_FREE_BLOCK //NEXT_FREE_BLOCK is gone
#define NEXT_FREE_BLOCK (TYPE_B + 200) //Now what? Same problem as before!
// ---end of RWW memory map---
This is why it isn't working.

Related

How "#define _CRTDBG_MAP_ALLOC" gets replaced by the preprocessor when there is no value for substitution?

I was using CRTDBG library to identify memory leaks in visual studio 2019. I need to define "#define _CRTDBG_MAP_ALLOC" macro for getting the line number of the leak occurs.
I am unclear that how the macro gets replaced when there is no value to be replaced ??
#define _CRTDBG_MAP_ALLOC
#include <iostream>
#include <crtdbg.h>
using namespace std;
int main()
{
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
int *ptr = (int*)malloc(sizeof(int));
*ptr = 10;
//free(ptr);
return 0;
}
I am a new to c/c++, Kindly help me on this.
#define _CRTDBG_MAP_ALLOC just tells the preprocessor that _CRTDBG_MAP_ALLOC is defined.
Code can later check if its defined with a #if defined(_CRTDBG_MAP_ALLOC).
Note nowhere do we set or care or check what value its defined to. So doing something like if (_CRTDBG_MAP_ALLOC == 2) doesn't make sense.
But we dont need it to. It just has to exist.
It's simply replaced by the empty string. E.g.
#define FOO 1
std::cout << FOO+1; // expands to 1+1, outputs 2
#undef FOO
#define FOO
std::cout << FOO+1; // expands to +1, outputs 1
But typically these things are checked with #ifdef.
This is the method I use and I prefer new and delete in C++:
#define new new(_CLIENT_BLOCK,__FILE__,__LINE__)
void GetMemoryLeak()
{
_CrtDumpMemoryLeaks();
}
And the program:
#define _CRTDBG_MAP_ALLOC
#include <iostream>
#include <crtdbg.h>
using namespace std;
#define new new(_CLIENT_BLOCK,__FILE__,__LINE__)
void GetMemoryLeak()
{
_CrtDumpMemoryLeaks();
}
int main()
{
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
int* ptr = new int;
*ptr = 10;
// delete ptr;
GetMemoryLeak();
return 0;
}
Output:
Detected memory leaks!
Dumping objects ->
C:...\Source.cpp(16) : {151} client block at 0x00F1CCB8, subtype 0, 4 bytes long.
Data: < > 0A 00 00 00
Object dump complete.
The program '[10452] Project7.exe' has exited with code 0 (0x0).

How to get a boolean indicating if a macro is defined or not?

My code is configurable with define macros. To get the value in the code, I'm doing this:
#ifdef CONFIG_X
static constexpr bool x = true;
#else
static constexpr bool x = false;
#endif
But this is quickly becoming very ugly in the code with several configuration variables...
Another solution I found is simply to cut the code in two:
#ifdef CONFIG_X
#define CONFIG_X_BOOL true
#else
#define CONFIG_X_BOOL false
#endif
static constexpr bool x = CONFIG_X_BOOL;
This is a bit better, but not really nice either.
Is there a nice way to have a boolean or a 1 or 0 if a macro is defined ?
This IS possible, but only in the limited case where you are looking for empty defines (as is often the case with compilation flags) or where you know the range of ways a flag will be defined, such as with a 0 or 1.
Here is working code:
#include <iostream>
// Define two genetic macros
#define SECOND_ARG(A,B,...) B
#define CONCAT2(A,B) A ## B
// If a macro is detected, add an arg, so the second one will be 1.
#define DETECT_EXIST_TRUE ~,1
// DETECT_EXIST merely concats a converted macro to the end of DETECT_EXIST_TRUE.
// If empty, DETECT_EXIST_TRUE converts fine. If not 0 remains second argument.
#define DETECT_EXIST(X) DETECT_EXIST_IMPL(CONCAT2(DETECT_EXIST_TRUE,X), 0, ~)
#define DETECT_EXIST_IMPL(...) SECOND_ARG(__VA_ARGS__)
// We will create MY_DEFINE, but not MY_DEFINE2
#define MY_DEFINE
int main()
{
// We can now use DETECT_EXIST to detect defines.
std::cout << "MY_DEFINE = " << DETECT_EXIST(MY_DEFINE) << std::endl;
std::cout << "MY_DEFINE2 = " << DETECT_EXIST(MY_DEFINE2) << std::endl;
}
This code will produce the output:
MY_DEFINE = 1
MY_DEFINE2 = 0
Since the first one does exist and the second doesn't.
If the macro is set to a value such as 1, you just need to have an alternate version of DETECT_EXIST_TRUE to handle it, with the macro value pasted on the end. For example:
#define DETECT_EXIST_TRUE1 ~,1
Then if you have:
#define MY_DEFINE1 1
Code like this will also work correctly in main:
std::cout << "MY_DEFINE1 = " << DETECT_EXIST(MY_DEFINE1) << std::endl;
#ifndef CONFIG_X
#error "Written for config x"
#endif
// True for config x, hack this about for other configurations
static bool x = 1;
Now it breaks if config is not x. Generally that's better than trying to second-guess what an unnamed configuration which is not X will require.

C++ Macro Arguments w/ Token Concatenation?

I have a bunch of labeled servos, each one has its own calibrated min, mid and max pulse-width value.
// repository of calibrated servo pulse width values:
#define SERVO_0x01_MIN 165
#define SERVO_0x01_MID 347
#define SERVO_0x01_MAX 550
#define SERVO_0x02_MIN 165
#define SERVO_0x02_MID 347
#define SERVO_0x02_MAX 550
...
To simplify maintenance of the code, swapping a servo should only require changing a single macro definition value.
// maps certain positions on robot to the servo that is installed there
#define JOINT_0 0x02
#define JOINT_1 0x05
#define JOINT_2 0x0A
...
// function-like macros to resolve values from mapping
#define GET_MIN(servo) SERVO_##servo##_MIN
#define GET_MID(servo) SERVO_##servo##_MID
#define GET_MAX(servo) SERVO_##servo##_MAX
The problem I'm having is that calling a function-like macro with an argument that itself is a macro does not resolve to its terminal value:
// main
int main(void) {
// this works
int max_0x01 = GET_MAX(0x01); // int max_0x01 = 550;
// this doesn't
int max_joint_0 = GET_MAX(JOINT_0); // int max_joint_0 = SERVO_JOINT_0_MAX;
}
What can I do to make GET_MAX(JOINT_0) turn into 550 ?
#define GET_MAX(servo) GET_MAX2(servo)
#define GET_MAX2(servo) SERVO_##servo##_MAX
The preprocessor will perform expansion (textual replacement) upon a variadic macro until it can expand no further. So passing in JOINT_0, such as GET_MAX(JOINT_0) will expand to
GET_MAX2(0x02)
This gets further expanded to
SERVO_0x02_MAX
And finally replaced with the #define value 550

Unexplained syntax error in Visual Studio

#ifndef _CXS_H
#define _CXS_H
#include <stdlib.h>
#include <limits.h>
#include <math.h>
#include <stdio.h>
#ifdef MATLAB_MEX_FILE
#include "mex.h"
#endif
#ifdef __cplusplus
#ifndef NCOMPLEX
#include <complex>
typedef std::complex<double> cs_complex_t ;
#endif
extern "C" {
#else
#ifndef NCOMPLEX
#include <complex.h>
#define cs_complex_t double _Complex
#endif
#endif
#define CS_VER 2 /* CXSparse Version */
#define CS_SUBVER 3
#define CS_SUBSUB 0
#define CS_DATE "Jun 1, 2012" /* CXSparse release date */
#define CS_COPYRIGHT "Copyright (c) Timothy A. Davis, 2006-2012"
#define CXSPARSE
#include "SuiteSparse_config.h"
#define cs_long_t SuiteSparse_long
#define cs_long_t_id SuiteSparse_long_id
#define cs_long_t_max SuiteSparse_long_max
........................
typedef struct cs_ci_sparse /* matrix in compressed-column or triplet form */
{
int nzmax ; /* maximum number of entries */
int m ; /* number of rows */
int n ; /* number of columns */
int *p ; /* column pointers (size n+1) or col indices (size nzmax) */
int *i ; /* row indices, size nzmax */
cs_complex_t *x ; /* numerical values, size nzmax */
int nz ; /* # of entries in triplet matrix, -1 for compressed-col */
} cs_ci ;
....................
#ifdef __cplusplus
}
#endif
#endif
I am getting a compilation error:
Error 1 error C2143: syntax error : missing ';' before '*'
for the line:
cs_complex_t *x ; /* numerical values, size nzmax */
Due to the size of the file some irrelevant parts are missing. Is there something that could explain this error given this code segment? This project is a simulator like Spice.
The code you've posted will lead to exactly this error if the macro NCOMPLEX is defined. Both definitions of cs_complex_t are enclosed in #ifndef NCOMPLEX. So if the macro NCOMPLEX is defined, cs_complex_t will not be defined and will thus be an unresolvable identifier when the compiler encounters it in the definition of cs_ci_sparse.
I'd say that's a logical bug in the file. If the definition of cs_complex_t depends on the absence of NCOMPLEX, all uses of cs_complex_t should depend on it too.

Print fully evaluated result of #define during compilation using #pragma message()

I have a quick question regarding printing the evaluated values of #defines using #pragma message. I'm using msvc++ in Visual Studio 2008.
Below is a simplified example:
#define __STR2__(x) #x
#define __STR1__(x) __STR2__(x)
#define WIDTH 10
#define HEIGHT 10
#define AREA (WIDTH * HEIGHT)
#pragma message("Area is: " __STR1__(AREA))
Now when I compile I get the following output:
>Area is: (10 * 10)
This is not exactly what I want. Is there any way to print out the evaluation of a #define expression so that I get:
>Area is: 100
during compilation. Perhaps this is not possible. Eventually I want to be able to cause a compiler error if the evaluated value is too large. i.e.
#if(AREA > 1000)
#pragma message(__ERROR__)
#endif
Some of my #defines use sizeof() which I believe causes issues in itself when evaluating conditionals - but that's a problem for the future!
I looked at the following post How do I show the value of a #define at compile time in gcc which is fine as long as the #define is defined as a value, and not a concatenation of other #defines.
The preprocessor won't do math for you, it can only substitute tokens and expand macros in a textual way.
If you want to calculate that value during compilation you should go for constexpr (http://en.cppreference.com/w/cpp/language/constexpr, more precisely this will hint the compiler to calculate it at compile-time)
#include <iostream>
#define WIDTH 10
#define HEIGHT 10
template<int a, int b>
constexpr int getArea() {
static_assert(a*b < 1000, "Area is too big");
return a*b;
}
const int area = getArea<WIDTH, HEIGHT>();
int main(void) {
std::cout << area;
}
Example
static_assert will do the check for the area if it is too large.
The precompiler can do limited math in #if statements. This may be sufficient for your needs:
#define WIDTH 10
#define HEIGHT 10
#define AREA (WIDTH * HEIGHT)
#if AREA > 1000
#error Oh bad, oh bad, oh bad
#endif
For more complex mathematics I would second what Marco A. said but you don't need that in a template or anything.
You can just put it up with all your #defines, for example:
#define WIDTH 10
#define HEIGHT 10
#define AREA (WIDTH * HEIGHT)
#define __ERROR__ "Oh bad, oh bad, oh bad"
static_assert(AREA < 1000, __ERROR__);
Or even simpler: static_assert(WIDTH * HEIGHT < 1000, "Oh bad, oh bad, oh bad");