c - 如何将指向结构的指针传递给在不同标头中描述的函数?
问题描述
我在单独的文件中声明和定义了结构,并且从 main 访问它们没有问题,但是当我尝试在函数中传递指向结构的指针时,这些函数又在其他文件中声明和定义,出现了问题:
In file included from func.c:1: func.h:4:22: warning: ‘struct StrA’ declared inside parameter list will not be visible outside of this definition or declaration
4 | void func(struct StrA *usrSet);
| ^~~~ func.c:5:6: error: conflicting types for ‘func’
5 | void func(struct StrA *usrSet){
| ^~~~ In file included from func.c:1: func.h:4:10: note: previous declaration of ‘func’ was here
4 | void func(struct StrA *usrSet);
| ^~~~
这是工作示例的代码:
//main.c
//------------------
#include <stdio.h>
#include "str.h"
#include "func.h"
int main(int argc, char const *argv[]){
myStr.a = 4;
myStr.b = 3;
printf("%d %d\n", myStr.a, myStr.b);
return 0;
}
//str.h
//-------------------------------
#ifndef STR_H
#define STR_H
struct StrA
{
int a;
int b;
};
extern struct StrA myStr;
#endif
//str.c
//----------------
#include "str.h"
struct StrA myStr;
但是,如果您添加一个函数(也在另一个块中描述)并尝试将一个指向结构的指针作为参数传递给它,我们将得到上述错误。
//main.c
//-----------------
#include <stdio.h>
#include "str.h"
#include "func.h"
int main(int argc, char const *argv[])
{
func(&myStr);
printf("%d %d\n", myStr.a, myStr.b);
return 0;
}
//func.h
//-----------------
#ifndef FUNC
#define FUNC
void func(struct StrA *usrSet);
#endif
//func.c
//----------------
#include "func.h"
#include "str.h"
struct StrA myStr;
void func(struct StrA *usrSet){
myStr.a = 1;
myStr.b = 9;
}
它们都包括相互关联的。str.h和str.c我不再赘述,不加帖子,它们保持不变。是否有一种通用且正确的方法可以连接到所描述的结构的外部,并且能够将它们作为指针。这个例子被人为地简化了,以便更容易理解我想要什么。
解决方案
推荐阅读
- regex - 正则表达式验证小数点前后的数字,不包括逗号
- ajax - 如何使用交叉获取在 reactjs 中修复 IE 中缓慢的 api 响应?
- sqlite - 你如何编写一个比较 SQLite 中几列的 when 子句?
- python - 使用余弦相似度获取带有潜在客户段落和 web_url 的 NewsId
- html - bulma 导航栏菜单默认在移动设备上打开
- javascript - 如何使用 xpath 获得硒中的非罢工价格金额?
- sql-server - 如何在 SSRS 中获取连接查询的列值?
- jquery - 如何在 Post 方法中获取模型内动态生成的复选框的值
- jakarta-ee - 如何在 thorntail 2.4 中将配置文件设置为默认值
- javascript - 在 Internet Explorer 中如果元素没有 tabIndex,它将返回 0 作为默认值