[英]using defined constant (from Makefile) to form a part of a variable name in C
是否可以使用定義的常量在C中形成變量名的一部分? 常量由Makefile定義。(實際上我想通過make參數傳遞它,如下所示)
例如,我想定義一個數字NUM
並使用它聲明一個變量。
#define NUM 5
/* I want to declare as below
int var5
using defined constant `NUM` above
*/
我試過了
int var ## NUM;
但##連接僅用於預處理宏操作,但不起作用。
實際上,常量NUM
在mycase中從Makefile(通過CFLAGS + = -DNUM = 5)傳入。
我怎樣才能做到這一點?
根據Shachar Shemesh的回答,我試過這個。
=== test.c
#include <stdio.h>
#define compound_id(name1, name2) name1##name2
int compound_id(mynum, NUM);
main()
{
mynum5 = 5;
printf("NUM = %d\n", NUM);
printf("mynum5 = %d\n", mynum5);
== Makefile
ifeq ($(NUM),5)
CFLAGS+=-DNUM=$(NUM)
endif
==命令
make test NUM=5
我得到以下結果:
ckim@stph45:/tmp] make test NUM=5
cc -DNUM=5 test.c -o test
test.c: In function 'main':
test.c:8: error: 'mynum5' undeclared (first use in this function)
test.c:8: error: (Each undeclared identifier is reported only once
test.c:8: error: for each function it appears in.)
make: *** [test] Error 1
怎么了?
:我也試過了,(沒有Makefile,只是運行make test
)
=== test.c
#include <stdio.h>
#define NUM 5
#define mynum(X) (int mynum##X;)
mynum(NUM)
main()
{
printf("NUM = %d\n", NUM);
mynum5 = 5;
printf("mynum5 = %d\n", mynum5);
}
並得到此錯誤:
ckim@stph45:/tmp] make test
cc test.c -o test
test.c:5: error: expected identifier or '(' before 'int'
make: *** [test] Error 1
您需要使用宏來使用預處理器的串聯。 但是,為了確保您的NUM
也經過預處理,您必須使用兩個級別的宏,例如:
#define CONCAT_IMPL(LHS, RHS) LHS ## RHS
#define CONCAT(LHS, RHS) CONCAT_IMPL(LHS, RHS)
參見Argument Prescan 。
#define compound_id(name1, name2) name1##name2
int compound_id(var, NUM);
您可以使用的一個選項是多級宏擴展。 嘗試這個:
#include <stdio.h>
/* This emulates the constant that comes from your makefile. */
#define NUM 5
/* This allows VAR2() to be called with the value of NUM (5)
instead of just the string "NUM". */
#define VAR(x) VAR2(x)
/* This actually concatenates 'var' and '5' to be 'var5'. */
#define VAR2(x) var##x
/* This allows you to stringify your variable name.
Again, we're using multilevel macro expansion so we get the
desired output string "var5" and not "VAR(NUM)". */
#define MACRO_STRINGIFY(x) STRINGIFY(x)
#define STRINGIFY(x) #x
int main(int argc, char **argv)
{
/* Declare your variable */
int VAR(NUM);
/* Assign a value to your variable */
VAR(NUM) = 7;
/* Print your variable name and its value */
printf(MACRO_STRINGIFY(VAR(NUM)) " = %d\n", VAR(NUM));
return 0;
}
這是輸出:
var5 = 7
如果您對輸出的原因感到困惑,那么這是main()
在預處理后(即所有宏擴展完成)但在編譯之前的樣子:
int main(int argc, char **argv)
{
int var5;
var5 = 7;
printf("var5" " = %d\n", var5);
return 0;
}
通過預處理源文件,您可以准確地看到宏變成了什么。 例如,如果您使用gcc
並且您的源文件是source.c
您可以像這樣預處理它,結果存儲在source.i
:
# gcc -E source.c -o source.i
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.