richliu’s blog

Linux, 工作, 生活.

richliu’s blog header image 2

GCC ## Preprocessor

February 8th, 2007 · No Comments

之前的程式有用到 ## 減少一些重複的程式, 當時是放在 kernel 2.4 上面, 用的是 gcc 2.95.3, 不過因為改寫到 kernel 2.6 的緣故, 所以 gcc 改用 3.4.6 . 這時就出現錯誤訊息了.

程式大概長得像是這樣.

#define amba_attr(name,fmt,arg...) \
static ssize_t show_##name##_test(struct device *_dev, struct device_attribute *attr, char *buf) \
{ \
struct amba_device *dev = to_amba_##name##(_dev); \
return sprintf(buf, fmt, arg); \
}

其實是個錯誤的語法, 要改成

#define amba_attr(name,fmt,arg...) \
static ssize_t show_##name##_test(struct device *_dev, struct device_attribute *attr, char *buf) \
{ \
struct amba_device *dev = to_amba_##name(_dev); \
return sprintf(buf, fmt, arg); \
}

這樣才對.

簡單的說, 如果 name 是要代換的字串, name之前是要保留的字串, 那就是要放 ##在前方,
EX: function_##name(arg);
如果 name 之後是要保留的字串, 那就是要放 ## 在後方
EX: name##_function(arg);
如果 name 是夾在中間. 那 ## 前後都要放
EX: function1_##name##_function2(arg);

原來我一直都搞錯, 那.... gcc 2.95.3 怎麼能過呀 :-/

ref.
GCC DOC 3.4.6 Concatenation

[Tags] Gcc, , [/Tags]

Tags: ,

Related posts

Tags: Linux · Programming

0 responses so far ↓

  • There are no comments yet...Kick things off by filling out the form below.

Leave a Comment