首页 > 解决方案 > 如何将指向结构的指针传递给在不同标头中描述的函数?

问题描述

我在单独的文件中声明和定义了结构,并且从 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我不再赘述,不加帖子,它们保持不变。是否有一种通用且正确的方法可以连接到所描述的结构的外部,并且能够将它们作为指针。这个例子被人为地简化了,以便更容易理解我想要什么。

标签: cstructure

解决方案


推荐阅读