#include <iostream>
#define MY_CONST 10
#define MY_OTHER_CONST MY_CONST
#undef MY_CONST
int main() {
enum my_enum : int {
MY_CONST = 100
};
std::cout << MY_OTHER_CONST;
return 0;
}
I would expect 10 as an output, but this program outputs 100. Can someone explain what is going on here?
https://godbolt.org/z/77EedG11x
#define MY_OTHER_CONST MY_CONST defines the macro MY_OTHER_CONST to have a replacement list of MY_CONST. No replacement is performed when defining a macro.
In std::cout << MY_OTHER_CONST;, MY_OTHER_CONST is replaced by its replacement list, becoming MY_CONST. At this point, there is no macro definition for MY_CONST, so no further replacement is performed. Then MY_CONST refers to the enum constant MY_CONST, which has value 100.
Related
I have read several articles about how Preprocessor directives work in C++.
It's clear to me that Preprocessor directives are managed by the pre-processor before compilation phase.
Let's consider this code:
#include <iostream>
#ifndef N
#define N 10
#endif
int main(){
int v[N];
return 0;
}
The Pre-processor will elaborate the source code by performing text replacement, so this code during compilation phase would be equivalent to:
int main(){
int v[10];
return 0;
}
Now my question is: Can I define a Macro by setting its value equal to a function?
It looks a bit weird to me but the answer is yes.
#include<iostream>
#include <limits>
#ifndef INT_MIN
#define INT_MIN std::numeric_limits<int>::min()
#endif
int get_max(){
return 5;
}
#ifndef INT_MAX
#define INT_MAX get_max()
#endif
int main()
{
std::cout << INT_MIN << " " << INT_MAX;
return 0;
}
Conceptually I'm not understanding why this code works, the pre-processor have to replace text before compilation phase, so how could a function be invoked (In this case get_max() function) ?
Functions invoking is a task managed by compiler? isn't it?
How could Pre-processor get access to std::numeric_limits::min()? This value is present inside the "limits" library, but if I understand correctly the libraries's inclusion is done by compiler.
For the sake of illustration I removed the includes from your code:
#ifndef INT_MIN
#define INT_MIN 0
#endif
int get_max(){
return 5;
}
#ifndef INT_MAX
#define INT_MAX get_max()
#endif
int main()
{
return INT_MIN + INT_MAX;
}
Then I invoked gcc with -E to see the output after preprocessing:
int get_max(){
return 5;
}
int main()
{
return 0 + get_max();
}
This is the code that will get compiled. The preprocessor does not call the funciton. It merely replaces INT_MAX with get_max().
Live Demo
Can I define a Macro by setting its value equal to a function?
Thats not what you do. #define INT_MAX get_max() just tells the preprocessor to replace INT_MAX with get_max(). The preprocessor doen't know nor care if get_max() is a function call or something else.
I would like to make a macro-like object that can detect its use in the current scope and behave differently in such a case. For example, consider the following fragment of code
#define FOO /* expand to printf("first time\n"); or printf("not a first time\n"); */
{
FOO // prints "first time"
FOO // prints "not a first time"
{
FOO // prints "first time"
FOO // prints "not a first time"
}
FOO // prints "not a first time"
}
Is it possible to make this with macro or any other language element in C++?
For people curious why I need this: I would like to make an easily copy-pastable macro FOO that I can put everywhere to get time spent in code fragment between two occurrences of it.
For example:
FOO // initialize timer
// code fragment 1
FOO // print the time spent in code fragment 1
// code fragment 2
FOO // print the time spent in code fragment 2
// code fragment 3
FOO // print the time spent in code fragment 3
You can create a scoped timer class:
#include <chrono>
#include <iostream>
#include <thread>
class ScopedTimer {
using clock = std::chrono::steady_clock;
std::chrono::time_point<clock> _begin;
public:
ScopedTimer() : _begin{ clock::now() }
{}
ScopedTimer(ScopedTimer const&) = delete;
ScopedTimer& operator=(ScopedTimer const&) = delete;
void print_duration() {
using namespace std::chrono;
auto const duration = duration_cast<milliseconds>(clock::now() - _begin);
std::cout << "Duration: " << duration.count() << '\n';
}
};
int main() {
ScopedTimer timer{};
std::this_thread::sleep_for(std::chrono::seconds(1));
timer.print_duration();
std::this_thread::sleep_for(std::chrono::seconds(1));
timer.print_duration();
}
How about this one?
#define FOO(block) /* The code section to time */ \
do{ \
/* code for start of timing */ \
{ block } \
/* code for end of timing */ \
while(0); \
C Preprocessor macros are often discouraged. Although in your case, you are using them to reduce the repetition of printf("first time\n"); and reducing repetition in code is a good thing. Assuming that we only want to consider macro-based solutions, this is what I would do:
#define FOO_FIRST printf("first time\n");
#define FOO_ADDITIONAL printf("not a first time\n");
{
FOO_FIRST // prints "first time"
FOO_ADDITIONAL // prints "not a first time"
{
FOO_FIRST // prints "first time"
FOO_ADDITIONAL // prints "not a first time"
}
FOO_ADDITIONAL // prints "not a first time"
}
Your originally-posted solution was trying to use a single FOO for both FOO_FIRST and FOO_ADDITIONAL, as a "convenience" to the macro-user. My suggestion is to resist the urge to crease such a "convenience", because what it really does is hide the fact that it is doing something different depending on which expansion it is. Don't hide that fact from the macro-user -- in my opinion, it's not a good thing to have the macro-user using a macro "without thinking". Instead, programmers should be thinking about the effects of the code that they write, and the resultant code is more readable when the usage of two separate macro names makes it clear that the programmer is doing two separate actions.
Using macros to reduce repetition is justifiable; using macros to obscure the programmer's intent is something I wouldn't do.
In your reply to one of the other potential solutions, you indicated that you wanted a macro to have an effect something like a context-sensitive function that was named Initialize_Or_Print(). This fact is an indication that you are going down the wrong road. Programming constructs should have single, clear purposes. Whenever you start to get the feeling that you are needing to cram too many separate purposes into one construct (Initialize_Or_Print_Or_SpawnNewPlayer_Or_BoilWater() is the direction you're headed), it's probably a bad thing and should be factored into separate pieces.
#define FOO { if(!foo_check) std::cout << "first time" << std::endl; else std::cout << "not a first time" << std::endl; foo_check=!foo_check; };
pretty obvious, i'd say, with the caveat to define
bool foo_check=false;
at the right level, for example at the start of the function, at start of main or as global variable for a file scope.
Said so, I use a timer class as per #Ayxan Haqverdili answer.
You can make a macro that modifies each time. (at least in gcc and I believe in msvc too):
// (only tried in gcc)
#define FLIPFLOP (__COUNTER__ % 2)
#define FOO std::cout <<(!FLIPFLOP ? "flip\n":"flop\n");
#include <iostream>
int main()
{
FOO
FOO
FOO
FOO
}
but you can't by nature make the preprocessor depend on source code block scope, since what { or } actually means is only determined later by the parser. The preprocessor knows nothing about it.
There are various proposals for "compiletime programming" for example http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/p2320r0.pdf, but whether they will address this type of use, I don't really know
Building on ...an answer that was deleted while I was typing this. You can get the timer behavior you want via RAII and macro expansion:
BuildConfig.hpp
//...
#ifdef _DEBUG
# undef PROFILE_BUILD
#else
# define PROFILE_BUILD
#endif
#define TOKEN_PASTE_SIMPLE(x, y) x##y
#define TOKEN_PASTE(x, y) TOKEN_PASTE_SIMPLE(x, y)
#define TOKEN_STRINGIZE_SIMPLE(x) #x
#define TOKEN_STRINGIZE(x) TOKEN_STRINGIZE_SIMPLE(x)
//...
ProfileLogScope.hpp
#pragma once
#include <chrono>
#include <string>
class ProfileLogScope {
public:
explicit ProfileLogScope(const char* scopeName) noexcept;
~ProfileLogScope() noexcept;
ProfileLogScope() = delete;
ProfileLogScope(const ProfileLogScope&) = delete;
ProfileLogScope(ProfileLogScope&&) = delete;
ProfileLogScope& operator=(const ProfileLogScope&) = delete;
ProfileLogScope& operator=(ProfileLogScope&&) = delete;
protected:
private:
using time_point_t = std::chrono::time_point<std::chrono::steady_clock>;
const char* _scope_name = nullptr;
time_point_t _time_at_creation{};
};
#if defined PROFILE_LOG_SCOPE || defined PROFILE_LOG_SCOPE_FUNCTION
#undef PROFILE_LOG_SCOPE
#undef PROFILE_LOG_SCOPE_FUNCTION
#endif
#ifdef PROFILE_BUILD
#define PROFILE_LOG_SCOPE(tag_str) ProfileLogScope TOKEN_PASTE(plscope_, __LINE__)(tag_str)
#define PROFILE_LOG_SCOPE_FUNCTION() PROFILE_LOG_SCOPE(__FUNCSIG__)
#else
#define PROFILE_LOG_SCOPE(tag_str)
#define PROFILE_LOG_SCOPE_FUNCTION()
#endif
ProfileLogScope.cpp
#include "ProfileLogScope.hpp"
#include <iostream>
#include <ostream>
#include <iomanip>
#include <sstream>
ProfileLogScope::ProfileLogScope(const char* scopeName) noexcept
: _scope_name(scopeName)
, _time_at_creation(std::chrono::steady_clock::now()) {
/* DO NOTHING */
}
ProfileLogScope::~ProfileLogScope() noexcept {
const auto now = std::chrono::steady_clock::now();
const auto elapsedTime = (now - _time_at_creation);
std::cout << "ProfileLogScope " << _scope_name << " took " << elapsedTime.count() << " nanoseconds.\n";
}
Usage
void Foo();
int main() {
PROFILE_LOG_SCOPE_FUNCTION()
{
PROFILE_LOG_SCOPE("Algorithm 1");
}
Foo();
}
void Foo() {
PROFILE_LOG_SCOPE_FUNCTION();
//...
}
The macros expand to unique-per-line variable names and are no-ops when explicitly not in a profiling mode.
When C++20's std::source_location becomes available, this will become a lot less messy. See Jason Turner's video on the topic: https://www.youtube.com/watch?v=TAS85xmNDEc
I have a project where there are two different preprocessor macros with the same name, defined in two different include files (from two different libraries), and I have to check if they have the same value at build time.
So far I could make this check at run time, assigning the macro values to different variables in different implementation files, each including only one of the headers involved.
How can I do it at build time?
This is what I tried so far (where Macro1.h and Macro2.h are third-party files I cannot modify):
Header files:
TestMultiMacros.h:
#ifndef TEST_MULTI_MACROS_H
#define TEST_MULTI_MACROS_H
struct Values
{
static const unsigned int val1, val2;
static const unsigned int c1 = 123, c2 = 123;
};
#endif // TEST_MULTI_MACROS_H
Macro1.h:
#ifndef MACRO1_H
#define MACRO1_H
#define MY_MACRO 123
#endif // MACRO1_H
Macro2.h:
#ifndef MACRO2_H
#define MACRO2_H
#define MY_MACRO 123
#endif // MACRO2_H
Implementation files:
TestMultiMacros1.cpp:
#include "TestMultiMacros.h"
#include "Macro1.h"
const unsigned int Values::val1 = MY_MACRO;
TestMultiMacros2.cpp:
#include "TestMultiMacros.h"
#include "Macro2.h"
const unsigned int Values::val2 = MY_MACRO;
entrypoint.cpp:
#include "TestMultiMacros.h"
using namespace std;
static_assert(Values::val1 == Values::val2, "OK"); // error: expression did not evaluate to a constant
static_assert(Values::c1 == Values::c2, "OK");
int main()
{
}
I would be interested in a solution using both C++11 and C++17.
Include the first header. Then save the value of the macro to a constexpr variable:
constexpr auto foo = MY_MACRO;
Then include the second header. It should silently override MY_MACRO. If your compiler starts complaining, do #undef MY_MACRO first.
Then compare the new value of the macro with the variable using a static_assert:
static_assert(foo == MY_MACRO, "whatever");
Here's a very simple C++17 test which works with arbitrary (non-function) macros by comparing the text of the macro expansion. For c++11, which lacks the constexpr comparison in std::string_view, you can write it yourself in a couple of lines, as shown in this answer.
#include <string_view>
#define STRINGIFY(x) STRINGIFY_(x)
#define STRINGIFY_(x) #x
#include "macro1.h"
//#define MY_MACRO A night to remember
constexpr const char* a = STRINGIFY(MY_MACRO);
#undef MY_MACRO
#include "macro2.h"
//#define MY_MACRO A knight to remember
constexpr const char* b = STRINGIFY(MY_MACRO);
static_assert(std::string_view(a) == b, "Macros differ");
int main() { }
(Godbolt: https://godbolt.org/z/nH5qVo)
Of course, this depends on what exactly you mean by equality of macros. This version will report failure if one header file has
#define MY_MACRO (2+2)
and the other has
#define MY_MACRO 4
Also worth noting that stringification normalises whitespace but it does not normalise the presence of whitespace other than trimming the ends. So (2 + 2) and (2 + 2) will compare as equal, but not (2+2) and ( 2 + 2 )
How to print macro name in c or c++
eg:
#define APINAME abc
#define PRINTAPI(x) printf("x")
I want to print PRINTAPI(APINAME) and not "abc"
Macros are pre-processors and they will be replaced by their associated statement before compiling the code. So, you have no chance to have the macro names in run-time. But, you can generate the string name in compile-time:
#define APINAME abc
#define PRINTAPI(x) std::cout << #x << std::endl;
int main()
{
PRINTAPI(APINAME);
}
Output
APINAME
In macros the operator # makes the input parameter to a string literal (stringify)
Since macros disappear when the preprocessor is doing it's work, which happens before the compiler is called, the APINAME will not exist anywhere in the source code for the compiler to deal with. The only solution is to come up with some sort of connection between the two in some other way, e.g.
struct foo{
const char *name;
const char *val;
} myvar = { "APINAME", APINAME };
With a macro, you can do this in as a one-liner:
#define APINAME "abc"
#define APINAME_VAR(x, y) struct foo x = { #y, y }
APINAME_VAR(myvar, APINAME)
or
cout << "APINAME=" << APINAME << endl
printf("APINAME=%s\n", APINAME);
Or, in the case of your macro:
#define PRINTAPI printf("%s=%s\n", #APINAME, APINAME)
will print APINAME=abc
I have two macros that declares class properties:
DECLARE_QUERY_PARAM_LONG(name)
DECLARE_QUERY_PARAM_STRING(name)
I want to count number of calls of this macros inside of my class and init
static const size_t paramsCount
with that number like this:
class MyClass {
...
DECLARE_QUERY_PARAM_LONG(param1)
DECLARE_QUERY_PARAM_STRING(param2)
DECLARE_QUERY_PARAM_STRING(param3)
DECLARE_QUERY_PARAM_LONG(param4)
static const size_t paramsCount = PARAMS_COUNT; // 4 in this case
...
};
Is this ever possible?
There would be a solution, rather complicated:
All your parameters will have a fixed name (say param)
You need to create one header file per type
You shall need boost
So here is the header creation file:
// file declare_int.h
#include BOOST_PP_UPDATE_COUNTER()
int stringize(param,BOOST_PP_COUNTER) ;
and the class file:
//file declare_auto.cpp
#include <boost/preprocessor/slot/counter.hpp>
#define _stringize(a,b) a##b
#define stringize(a,b) _stringize(a,b)
// reset counter
#if defined(BOOST_PP_COUNTER)
#undef BOOST_PP_COUNTER
#endif
class A {
public:
#include "declare_int.h"
#include "declare_int.h"
#include "declare_int.h"
#include "declare_int.h"
static const int nbParams = BOOST_PP_COUNTER ;
};
and finally the output of:
g++ -E -P -c declare_auto.cpp -IPATH_TO_BOOST
is
class A {
public:
int param1 ;
int param2 ;
int param3 ;
int param4 ;
static const int nbParams = 4 ;
};
You can at least count number of lines in the following way:
class MyClass
{
static const int line_1 = __LINE__;
DECLARE_QUERY_PARAM_LONG(param1)
DECLARE_QUERY_PARAM_STRING(param2)
DECLARE_QUERY_PARAM_STRING(param3)
DECLARE_QUERY_PARAM_LONG(param4)
static const int line_2 = __LINE__;
static const int macro_calls = line_2 - line_1 - 1;
public:
MyClass()
{
cout << macro_calls << endl;
}
};
But I think you'll need C++11 to do that. And You cannot have empty lines within those two __LINE__s. Otherwise, you'll have to count those empty lines as well.
As such no.
What you are asking for would require some form of introspection, which is not natively supported by C++.
You can improve the macro though, if you had:
DECLARE_QUERY_PARAMS(((LONG , param1))
((STRING, param2))
((STRING, param3))
((LONG , param4)))
then you could do what you want.
You can have a look at Boost.Preprocessor to learn how to obfuscate your sources this way.
Note: this uses a Sequence, in boost parlance.
I don't think there's a standard way to do this, but the DevStudio compiler has this preprocessor macro:
__COUNTER__
Expands to an integer starting with 0 and incrementing by 1 every time it is used in a compiland. __COUNTER__ remembers its state when using precompiled headers. If the last __COUNTER__ value was 4 after building a precompiled header (PCH), it will start with 5 on each PCH use.
__COUNTER__ lets you generate unique variable names. You can use token pasting with a prefix to make a unique name. For example:
// pre_mac_counter.cpp
#include <stdio.h>
#define FUNC2(x,y) x##y
#define FUNC1(x,y) FUNC2(x,y)
#define FUNC(x) FUNC1(x,__COUNTER__)
int FUNC(my_unique_prefix);
int FUNC(my_unique_prefix);
No. Macro's don't respect scope at all, and don't understand that they're inside a class.
No. Macros aren't executed, they're expanded and not even by compiler, but by preprocessor.