Answer the question
In order to leave comments, you need to log in
How to create through macros a unique prefix to the generated type name at the compilation stage?
I'm trying to make a system to perform actions before the main() function is run. Needed to register meta-information about classes. I decided to do it through global variables in cpp files:
// Работает за счёт выполнения кода конструктора при инициализации глобальной переменной. До main
class BeforeMainHelper { public: BeforeMainHelper() { /* Before main start actions */ } } __helper__;
Answer the question
In order to leave comments, you need to log in
You don't need to use __FILE__ , just put the classes in anonymous namespaces. Such classes will be unique for each compilation unit. Then it will be enough just to fasten __LINE__ to the identifier of the class object. And the class itself, alas, will have to be defined by a separate macro, since you need the ability to create several objects.
Here is a small example. Three file project.
The trick with concatenating a number and an identifier using macros is taken from here:
stackoverflow.com/questions/1597007/creating-c-mac...
"header.hpp":
#ifndef HEADER_HPP_INCLUDED
#define HEADER_HPP_INCLUDED
#include <iostream>
#define TOKENPASTE(x, y) x ## y
#define TOKENPASTE2(x, y) TOKENPASTE(x, y)
#define CLASS_MAGIC \
namespace \
{ \
struct FixedNameClass \
{ \
explicit FixedNameClass(int line) \
{ \
std::cout << "Hello from \"" << __FILE__ << \
"\", line " << line << std::endl; \
} \
}; \
}
#define OBJECT_MAGIC \
namespace \
{ \
FixedNameClass TOKENPASTE2(variable_name_object, __LINE__)(__LINE__); \
}
#endif // HEADER_HPP_INCLUDED
#include "header.hpp"
CLASS_MAGIC
OBJECT_MAGIC
OBJECT_MAGIC
OBJECT_MAGIC
int main()
{
}
OBJECT_MAGIC
OBJECT_MAGIC
#include "header.hpp"
CLASS_MAGIC
OBJECT_MAGIC
OBJECT_MAGIC
Hello from "other.cpp", line 4
Hello from "other.cpp", line 5
Hello from "main.cpp", line 4
Hello from "main.cpp", line 5
Hello from "main.cpp", line 6
Hello from "main.cpp", line 12
Hello from "main.cpp", line 13
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question