[英]How to “#define” this variable?
I have one integer value in 0x102 address and i need to create #define ABC ...
macro. 我在0x102地址中有一个整数值,我需要创建#define ABC ...
宏。
ABC is variable or something (with access to 0x102 cell). ABC是变量或其他内容(可访问0x102单元)。
It must be possible to do operations like this : 必须可以执行以下操作:
ABC = 666;
int x = ABC*2 + 4;
int *p = &ABC;
Can you help me ? 你能帮助我吗 ?
假设您的对象是16位(地址0x102是2字节对齐):
#define ABC (*(volatile uint16_t *) 0x102)
You can do it like this: 您可以这样做:
#define ABC *((int*)0x102)
int main() {
ABC = -1;
return 0;
}
It set an int*
and then deferences it all in one go. 它设置了一个int*
,然后一次性引用了所有内容。
If you have the address as a constant, you can write: 如果您将地址作为常量,则可以编写:
#define ABC (*(int *)0x102)
If you have a variable in that address (with a name such as my_variable
): 如果您在该地址中有一个变量(名称如my_variable
):
What you want is what C++ calls references. 您想要的是C ++调用的引用。 In C, it doesn't exist. 在C中,它不存在。 However, you could, as you guessed, use a macro for it. 但是,您可以像您猜到的那样使用宏。
If this variable is in the same scope as ABC
, all you need is: 如果此变量与ABC
处于同一范围内,则您需要做的是:
#define ABC my_variable
If you have a pointer to this variable (for example as a function argument), you can write something like this: 如果您有一个指向此变量的指针(例如,作为函数参数),则可以编写如下内容:
#define ABC (*that_argument)
As compile time the compiler replaces the #defined variable with the actual value. 在编译时,编译器将#defined变量替换为实际值。
So, If you #define ABC
因此,如果您#define ABC
1) ABC = 666;
1) ABC = 666;
You wont be able to perform this operation. 您将无法执行此操作。
2) int x = ABC*2 + 4;
2) int x = ABC*2 + 4;
You will be able to perfrom this operation 您将可以执行此操作
3) int *p = &ABC;
3) int *p = &ABC;
You wont be able to perform this operation. 您将无法执行此操作。
You can do that by adding compile time macros. 您可以通过添加编译时宏来实现。 You can add ABC=(*(int*)0x102)
it in Preprocessor field in project settings if you are using IDE. 如果使用的是IDE,则可以在项目设置的“预处理器”字段中添加ABC=(*(int*)0x102)
。 Or else if you are using CLI compiler, for example gcc
you can compile the program as below. 否则,如果使用的是CLI编译器(例如gcc
,则可以按以下方式编译程序。
gcc prog.c -DABC=(*(int*)0x102)
Or you can define it directly in the program also like below 或者您也可以在程序中直接定义它,如下所示
#define ABC (*(int *)0x102)
int main()
{
ABC = 666;
int x = ABC*2 + 4;
int *p = &ABC;
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.