【问题标题】:warning: ‘struct task_struct’ "Declared inside parameter list will not be visible outside of this definition or declaration"警告:‘struct task_struct’“在参数列表中声明的在此定义或声明之外将不可见”
【发布时间】:2021-06-29 22:00:27
【问题描述】:

我有以下代码:

文件 sched.h

   #ifndef __SCHED_H__
   #define __SCHED_H__
   #include <stats.h>
   truct task_struct {
       ...
       struct stats stat;
   };
   #endif

文件 stats.h

   #ifndef STATS_H
   #define STATS_H
   #include <sched.h>
   struct stats
   {
   ...
   };

   void initStats (struct task_struct* tsk);
   #endif

当我尝试编译时,它给了我以下警告

警告:在参数列表中声明的“struct task_struct”在此定义或声明之外将不可见 17 | void initStats (struct task_struct* tsk);

我已经看到发布了类似的问题,但我无法解决问题。我想知道问题是否是因为两个文件相互包含。任何帮助将不胜感激:)。

编辑:我在代码中更改了几处。现在,我不使用 task_struct 作为参数,而是使用 struct stats。但是现在 sched.h 文件找不到 struct stats 的声明。我不知道如何解决这个问题。由于编译器给我的错误不同,我发布了一个新问题:Problem with declaration of structs in header files: "error: field 'stat' has incimplete type"

【问题讨论】:

  • 你的标题中没有包含保护吗?他们真的会无条件地总是循环地包含彼此吗?这是缺少的重要信息。
  • 您的问题是由您的标题的循环包含引起的。如果您首先包含sched.h,它将包含stats.h。假设你确实有包含守卫,在stats.h 中,编译器将在没有看到sched.h 之前的声明的情况下到达函数声明。
  • 尝试解决循环依赖或添加弗拉德回答中提到的前向声明。
  • 是的,包括在内。感谢您指出,我已经编辑了问题。

标签: c struct scope header-files declaration


【解决方案1】:

似乎之前在文件范围内声明的结构struct task_struct在函数声明处是不可见的。

如果是,那么在这个函数声明中

void initStats (struct task_struct* tsk);

类型说明符struct task_struct 具有函数原型范围,在函数原型之外不可见。

就是这个类型说明符和类型说明符不一样

struct task_struct {
   ...
   struct stats stat;

};

在函数原型之外声明。

来自 C 标准(6.2.1 标识符范围)

  1. ...同一个标识符可以在不同的点表示不同的实体 在节目中。

  1. ...如果出现声明标识符的声明符或类型说明符 在函数的参数声明列表中 原型(不是函数定义的一部分),标识符有 函数原型作用域,在函数结束时终止 声明符

这是一个重现编译器消息的演示程序。

#include <stdio.h>

//  struct A;

void f( struct A );

struct A
{
    int x;
};

int main(void) 
{
    return 0;
}

prog.c:5:16: error: ‘struct A’ declared inside parameter list will not be visible outside of this definition or declaration [-Werror]
 void f( struct A );
                ^

如果取消注释前向声明

//  struct A;

然后错误信息就会消失。

【讨论】:

  • 为什么会这样?程序不应该采用包含在 sched.h 文件中声明的类型说明符吗?为什么要声明一个不同的?
  • @shayminshaymin 您的代码中似乎有错字并且结构名称不一样,或者编译器没有看到之前的结构声明。
  • 好像是后者。如果我将函数移动到 sched.h 文件,它不会给出任何警告或错误。
  • 您在示例中显示的是正在发生的事情,但我不知道如何解决它。我已经更改了代码中的一些内容,我将发布一个关于它的新问题。我会在问题本身中指出这一点。
  • @shayminshaymin 您可以选择最佳答案关闭问题,然后提出一个新问题,您将在其中提供重现错误的最小完整程序。
猜你喜欢
  • 2021-01-14
  • 1970-01-01
  • 2022-06-14
  • 1970-01-01
  • 2011-12-07
  • 2012-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多