【问题标题】:Why this program is compiling with gcc but not with g++?为什么这个程序用 gcc 编译而不用 g++ 编译?
【发布时间】:2014-01-10 08:54:09
【问题描述】:

以下程序使用 gcc 而不是 g++ 编译,我只生成目标文件。

这是 prog.c:

#include "prog.h"

static struct clnt_ops tcp_nb_ops = {4}; 

这是 prog.h:

#ifndef _PROG_
#define _PROG_

#include <rpc/rpc.h>

#endif

当我这样做时:

gcc -c prog.c

生成目标代码,但是,

g++ -c prog.c

给出错误:

variable ‘clnt_ops tcp_nb_ops’ has initializer but incomplete type

如何解决这个问题?

【问题讨论】:

  • 结构的定义在哪里???在 C 中我们可以定义这样的结构吗?在 c++ 中我认为这是不可能的。

标签: c++ c gcc g++


【解决方案1】:

clnt.h中这个结构体的定义:

typedef struct CLIENT CLIENT;
struct CLIENT {
  AUTH  *cl_auth;        /* authenticator */
  struct clnt_ops {
    enum clnt_stat (*cl_call) (CLIENT *, u_long, xdrproc_t, caddr_t, xdrproc_t, caddr_t, struct timeval);
    /* ...*/
  } *cl_ops;
    /* ...*/
};

如您所见,struct clnt_ops 定义在内部 struct CLIENT。所以这个类型在 C++ 中的正确名称是CLIENT::clnt_ops。然而,在 C 中没有嵌套结构之类的东西,因此它可以简单地显示为 struct clnt_ops

如果您想要便携,您可以添加以下内容:

#ifdef __cplusplus
    typedef CLIENT::clnt_ops clnt_ops;
#else
    typedef struct clnt_ops clnt_ops;
#endif

clnt_ops tcp_nb_ops = ...;

但我认为这种类型根本不打算由客户端代码直接使用。而是仅使用整个 struct CLIENT

【讨论】:

  • 感谢g++,但是如果c中没有嵌套结构这样的东西,那么它不应该抛出一些错误吗?
  • @Sumit:我没有解释自己。在 C 中,您可以在另一个结构中定义一个结构,但所有结构名称都将在全局命名空间中可见,因为这是唯一的命名空间。但是,使用内部结构定义的变量将是结构的适当成员。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-15
相关资源
最近更新 更多