[英]Macro to refer to struct member, homegrown complex type to standard C99 complex conversion
我正在重新編寫用C語言編寫的大型科學應用程序的內部知識,以便將本地的MyComplex
類型及其關聯的例程替換為使用C99 complex
類型的算法。
有些簡單,例如
#ifdef HAVE_COMPLEX_H
#include <complex.h>
#define double complex MyComplex
#define ComplexAddition(a, b) ((a) + (b))
#define ComplexConjugation(a) (conj(a))
#else
/* very old code, used everywhere in the project */
struct MyComplex { double re, double im };
typedef struct MyComplex MyComplex;
MyComplex ComplexAddition(MyComplex a, MyComplex b) { ... }
MyComplex ComplexConjugation(MyComplex a) { ... }
#endif
那一點行得通,我對此很滿意,但是在MyComplex
結構中偷看了一些例程,所以我認為我很聰明,並用RealPart(c)
替換了每次出現的c.re
,其中
#ifdef HAVE_COMPLEX_H
#define RealPart(c) creal(c)
#else
#define RealPart(c) c ## .re
#endif
(與ImagPart(c)
和im
成員類似)。
如果定義了HAVE_COMPLEX_H
,這將非常出色,但是如果我嘗試在HAVE_COMPLEX_H
設置HAVE_COMPLEX_H
進行編譯,則Mac(clang 7.3.0)上的Clang編譯器會說:
utils.c:13505:9: error: pasting formed '].', an invalid preprocessing token
RealPart(m[row][dim - 1]), ImagPart(m[row][dim - 1]));
^
./utils.h:39:23: note: expanded from macro 'RealPart'
#define RealPart(c) c ## .re
^
utils.c:13505:36: error: pasting formed '].', an invalid preprocessing token
RealPart(m[row][dim - 1]), ImagPart(m[row][dim - 1]));
^
./utils.h:40:23: note: expanded from macro 'ImagPart'
#define ImagPart(c) c ## .im
^
同樣,GNU 4.2.1編譯器(在OpenBSD上)表示
utils.c:9968:1: error: pasting "sum" and "." does not give a valid preprocessing token
utils.c:9968:1: error: pasting "sum" and "." does not give a valid preprocessing token
utils.c:10059:1: error: pasting "]" and "." does not give a valid preprocessing token
我似乎無法正確定義宏,並且我開始懷疑是否有可能創建一個擴展為結構成員的宏。
我可能忽略了一些簡單的事情...
問題是##
連接字符串,而RealPart()
和ImagPart()
的參數不是字符串。
正確的宏定義(當HAVE_COMPLEX_H
時)
#define RealPart(c) c.re
#define ImagPart(c) c.im
對我來說有點太明顯了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.