문제

For example:

A.h contains:

#define DRAWING_OBJECTS_COUNT 4

B.h contains:

#include "A.h"
int arrayExample[DRAWING_OBJECTS_COUNT];

When I try this, the console says that

DRAWING_OBJECTS_COUNT

is undefined in class B.

What is the best way to let class B know the constant from class A? Also, does the preprocessor directives only apply to the file it is written in?

도움이 되었습니까?

해결책

As it is posted, the code should work (this doesn't mean it's good code though). Your issue is probably a circular include (most likely), or a subsequent #undef.

What is the best way to let class B know the constant from class A?

Use a const int instead, or an enum value - defines are so old-school.

Also, does the preprocessor directives only apply to the file it is written in?

It depends - if defined in a file, it applies to that translation unit, from its point of declaration onwards - meaning you can define it in a header, and it will be visible in files that include that header. You can also define preprocessor directives using compiler options, which makes them visible for all files compiled.

다른 팁

Pre processor directives know no scope. Every occurrence of the token after the #define will be replaced, irrespective of file, class, whatever, right until you get a #undef of that token, or until all of the input is read by the compiler.

If you want to indicate that DRAWING_OBJECTS_COUNT is related to the class A in some way, declare it inside A as a const int or enum.

Could you post the exact error message and source code line, and check for #undefs. And make sure you are including A.h

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top