IT박스

전 처리기 매크로가 왜 사악하고 대안은 무엇입니까?

itboxs 2020. 9. 21. 07:29
반응형

전 처리기 매크로가 왜 사악하고 대안은 무엇입니까?


나는 항상 이것을 물었지만 정말 좋은 대답을받지 못했습니다. 나는 첫 번째 "Hello World"를 작성하기 전에 거의 모든 프로그래머가 "매크로는 절대 사용해서는 안된다", "매크로는 사악하다"와 같은 문구를 접했다고 생각합니다. 내 질문은 다음과 같습니다. 왜? 새로운 C ++ 11을 사용하면 수년이 지난 후에 진정한 대안이 있습니까?

쉬운 부분은 #pragma플랫폼과 컴파일러에 특화된, 같은 매크로에 관한 것 입니다. 그리고 대부분의 경우 #pragma once, 최소한 두 가지 중요한 상황에서 오류가 발생하기 쉬운 심각한 결함 이 있습니다. 다른 경로에 동일한 이름과 일부 네트워크 설정 및 파일 시스템이 있습니다.

그러나 일반적으로 매크로와 그 사용에 대한 대안은 어떻습니까?


매크로는 다른 도구와 같습니다. 살인에 사용되는 망치는 망치이기 때문에 악의가 없습니다. 그 사람이 그런 식으로 사용하는 방식은 악합니다. 못으로 망치고 싶다면 망치가 완벽한 도구입니다.

매크로를 "나쁜"것으로 만드는 몇 가지 측면이 있습니다 (나중에 각각에 대해 자세히 설명하고 대안을 제안 할 것입니다).

  1. 매크로를 디버그 할 수 없습니다.
  2. 매크로 확장은 이상한 부작용을 일으킬 수 있습니다.
  3. 매크로에는 "네임 스페이스"가 없으므로 다른 곳에서 사용되는 이름과 충돌하는 매크로가있는 경우 원하지 않는 위치에서 매크로가 대체되고 일반적으로 이상한 오류 메시지가 표시됩니다.
  4. 매크로는 인식하지 못하는 것에 영향을 미칠 수 있습니다.

여기에서 조금 확장 해 보겠습니다.

1) 매크로는 디버깅 할 수 없습니다. 숫자 나 문자열로 변환되는 매크로가 있으면 소스 코드에 매크로 이름이 있고 많은 디버거가 매크로가 무엇으로 변환되는지 "볼"수 없습니다. 그래서 당신은 실제로 무슨 일이 일어나고 있는지 알지 못합니다.

교체 : 사용 enum또는const T

"함수와 유사한"매크로의 경우 디버거가 "현재있는 소스 행당"수준에서 작동하기 때문에 매크로가 하나의 명령문이든 100 개이든 상관없이 단일 명령문처럼 작동합니다. 무슨 일이 일어나고 있는지 파악하기 어렵게 만듭니다.

대체 : 함수 사용- "빠름"이 필요한 경우 인라인 (하지만 너무 많은 인라인은 좋지 않음)

2) 매크로 확장은 이상한 부작용을 일으킬 수 있습니다.

유명한 것은 #define SQUARE(x) ((x) * (x))그리고 사용 x2 = SQUARE(x++)입니다. 이로 x2 = (x++) * (x++);인해 유효한 코드 [1]이더라도 프로그래머가 원하는 바가 거의 확실하지 않습니다. 함수라면 x ++를해도 괜찮을 것이고 x는 한 번만 증가 할 것입니다.

또 다른 예는 매크로의 "if else"입니다.

#define safe_divide(res, x, y)   if (y != 0) res = x/y;

그리고

if (something) safe_divide(b, a, x);
else printf("Something is not set...");

실제로 완전히 잘못된 것이됩니다 ....

교체 : 실제 기능.

3) 매크로에는 네임 스페이스가 없습니다.

매크로가있는 경우 :

#define begin() x = 0

그리고 begin을 사용하는 C ++ 코드가 있습니다.

std::vector<int> v;

... stuff is loaded into v ... 

for (std::vector<int>::iterator it = myvector.begin() ; it != myvector.end(); ++it)
   std::cout << ' ' << *it;

이제 어떤 오류 메시지가 발생한다고 생각하고 오류를 어디에서 찾습니까 (다른 사람이 작성한 헤더 파일에있는 시작 매크로를 완전히 잊었거나 알지 못했다고 가정 할 때)? [포함하기 전에 해당 매크로를 포함하면 훨씬 더 재미 있습니다. 코드 자체를 볼 때 전혀 의미가없는 이상한 오류에 빠져들 것입니다.

대체 : "규칙"만큼 대체하는 것은 없습니다. 매크로에는 대문자 이름 만 사용하고 다른 항목에는 대문자 이름을 모두 사용하지 마십시오.

4) 매크로에는 사용자가 알지 못하는 효과가 있습니다.

이 기능을 사용하십시오.

#define begin() x = 0
#define end() x = 17
... a few thousand lines of stuff here ... 
void dostuff()
{
    int x = 7;

    begin();

    ... more code using x ... 

    printf("x=%d\n", x);

    end();

}

이제 매크로를 보지 않고도 begin이 x에 영향을 미치지 않는 함수라고 생각할 것입니다.

이런 종류의 것, 그리고 훨씬 더 복잡한 예제를 보았습니다. 정말 당신의 하루를 망칠 수 있습니다!

Replacement: Either don't use a macro to set x, or pass x in as an argument.

There are times when using macros is definitely beneficial. One example is to wrap a function with macros to pass on file/line information:

#define malloc(x) my_debug_malloc(x, __FILE__, __LINE__)
#define free(x)  my_debug_free(x, __FILE__, __LINE__)

Now we can use my_debug_malloc as the regular malloc in the code, but it has extra arguments, so when it comes to the end and we scan the "which memory elements hasn't been freed", we can print where the allocation was made so the programmer can track down the leak.

[1] It is undefined behaviour to update one variable more than once "in a sequence point". A sequence point is not exactly the same as a statement, but for most intents and purposes, that's what we should consider it as. So doing x++ * x++ will update x twice, which is undefined and will probably lead to different values on different systems, and different outcome value in x as well.


The saying "macros are evil" usually refers to the use of #define, not #pragma.

Specifically, the expression refers to these two cases:

  • defining magic numbers as macros

  • using macros to replace expressions

with the new C++ 11 there is a real alternative after so many years ?

Yes, for the items in the list above (magic numbers should be defined with const/constexpr and expressions should be defined with [normal/inline/template/inline template] functions.

Here are some of the problems introduced by defining magic numbers as macros and replacind expressions with macros (instead of defining functions for evaluating those expressions):

  • when defining macros for magic numbers, the compiler retains no type information for the defined values. This can cause compilation warnings (and errors) and confuse people debugging the code.

  • when defining macros instead of functions, programmers using that code expect them to work like functions and they do not.

Consider this code:

#define max(a, b) ( ((a) > (b)) ? (a) : (b) )

int a = 5;
int b = 4;

int c = max(++a, b);

You would expect a and c to be 6 after the assignment to c (as it would, with using std::max instead of the macro). Instead, the code performs:

int c = ( ((++a) ? (b)) ? (++a) : (b) ); // after this, c = a = 7

On top of this, macros do not support namespaces, which means that defining macros in your code will limit the client code in what names they can use.

This means that if you define the macro above (for max), you will no longer be able to #include <algorithm> in any of the code below, unless you explicitly write:

#ifdef max
#undef max
#endif
#include <algorithm>

Having macros instead of variables / functions also means that you cannot take their address:

  • if a macro-as-constant evaluates to a magic number, you cannot pass it by address

  • for a macro-as-function, you cannot use it as a predicate or take the function's address or treat it as a functor.

Edit: As an example, the correct alternative to the #define max above:

template<typename T>
inline T max(const T& a, const T& b)
{
    return a > b ? a : b;
}

This does everything the macro does, with one limitation: if the types of the arguments are different, the template version forces you to be explicit (which actually leads to safer, more explicit code):

int a = 0;
double b = 1.;
max(a, b);

If this max is defined as a macro, the code will compile (with a warning).

If this max is defined as a template function, the compiler will point out the ambiguity, and you have to say either max<int>(a, b) or max<double>(a, b) (and thus explicitly state your intent).


A common trouble is this :

#define DIV(a,b) a / b

printf("25 / (3+2) = %d", DIV(25,3+2));

It will print 10, not 5, because the preprocessor will expand it this way:

printf("25 / (3+2) = %d", 25 / 3 + 2);

This version is safer:

#define DIV(a,b) (a) / (b)

Macros are valuable especially for creating generic code (macro's parameters can be anything), sometimes with parameters.

More, this code is placed (ie. inserted) at the point of the macro is used.

OTOH, similar results may be achived with:

  • overloaded functions (different parameter types)

  • templates, in C++ (generic parameter types and values)

  • inline functions (place code where they are called, instead of jumping to a single-point definition -- however, this is rather a recommandation for the compiler).

edit: as for why the macro are bad:

1) no type-checking of the arguments (they have no type), so can be easily misused 2) sometimes expand into very complex code, that can be difficult to identify and understand in the preprocessed file 3) it is easy to make error-prone code in macros, such like:

#define MULTIPLY(a,b) a*b

and then call

MULTIPLY(2+3,4+5)

that expands in

2+3*4+5 (and not into: (2+3)*(4+5)).

To have the latter, you should define:

#define MULTIPLY(a,b) ((a)*(b))

I don't think that there is anything wrong with using preprocessor definitions or macros as you call them.

They are a (meta) language concept found in c/c++ and like any other tool they can make your life easier if you know what you're doing. The trouble with macros is that they are processed before your c/c++ code and generate new code that can be faulty and cause compiler errors which are all but obvious. On the bright side they can help you keep your code clean and save you a lot of typing if used properly, so it comes down to personal preference.


I think that the problem is that macros are not well optimized by the compiler and are "ugly" to read and debug.

Often a good alternatives are generic functions and/or inline functions.


Macros in C/C++ can serve as an important tool for version control. Same code can be delivered to two clients with a minor configuration of Macros. I use things like

#define IBM_AS_CLIENT
#ifdef IBM_AS_CLIENT 
  #define SOME_VALUE1 X
  #define SOME_VALUE2 Y
#else
  #define SOME_VALUE1 P
  #define SOME_VALUE2 Q
#endif

This kind of functionality is not so easily possible without macros. Macros are actually a great Software Configuration Management Tool and not just a way to create shortcuts for reuse of code. Defining functions for the purpose of reusability in macros can definitely create problems.


Preprocessor macros are not evil when they are used for intended purposes like:

  • Creating different releases of the same software using #ifdef type of constructs, for example the release of windows for different regions.
  • For defining code testing related values.

Alternatives- One can use some sort of configuration files in ini,xml,json format for similar purposes. But using them will have run time effects on code which a preprocessor macro can avoid.

참고URL : https://stackoverflow.com/questions/14041453/why-are-preprocessor-macros-evil-and-what-are-the-alternatives

반응형