c中类型的重新定义,但包括守卫?

Redefinition of type in c, but guard is included?

我有无法在一台计算机上编译的代码。它在我的电脑上工作,但在另一台电脑上不起作用。错误是 "redefinition of typdef cplx",即使我对每个头文件都有保护并且我对 typdef 的每个定义都有保护:

#ifdef __cplusplus
#include <complex>
#include <cmath>
typedef std::complex<double> cplx;
#else
#include <tgmath.h>
typedef double complex cplx;
#endif

为什么会出现这个问题? 这里有两个头文件。 blas.h:

#ifndef BLAS_H
#define BLAS_H
#ifdef __cplusplus
#include <complex>
#include <cmath>
typedef std::complex<double> cplx;
#else
#include <tgmath.h>
typedef double complex cplx;
#endif
//declaration of functions
#endif

和lapack.h:

#ifndef LAPACK_H
#define LAPACK_H
#ifdef __cplusplus
#include <complex>
#include <cmath>
typedef std::complex<double> cplx;
#else
#include <tgmath.h>
typedef double complex cplx;
#endif
//declarations of functions
#endif

问题是当我同时包含 lapack.h 和 blas.h 时,我得到了这个错误?

你的守卫防止同一个包含文件被包含两次,但是你有两个不同的包含文件和两个不同的守卫,并且你在每个文件中定义 cplx

您需要在每个包含文件中为该类型设置单独的防护,如下所示:

#ifndef CPLX
#define CPLX
#ifdef __cplusplus
#include <complex>
#include <cmath>
typedef std::complex<double> cplx;
#else
#include <tgmath.h>
typedef double complex cplx;
#endif
//declarations of functions
#endif