【问题标题】:How and where to call externally defined struct如何以及在何处调用外部定义的结构
【发布时间】:2012-04-26 13:05:30
【问题描述】:

文件:element.h

#ifndef ELEMENT_H
#define ELEMENT_H 

typedef struct Elem {
  char * itag;
  char * cont;
  char * etag;
  struct Elem * previous;
} Element;

void printElement ( Element * );
#endif /* ELEMENT_H */

我在 element.h 和 element.c 中声明并定义了一个结构 Element(未显示,但在其中执行了 malloc)。

文件parser.c 的功能之一应该访问Element。 如果某些条件适用,则会创建一个指向Element 的新指针,并填充其中一个指针属性。 之后的一些迭代,如果其他条件适用,另一个指针属性会得到一些文本。 然后,当满足其他条件时,指向Element 的指针应该被传递给另一个文件的函数:output.c

我的问题是:我应该如何以及在哪里打电话给Element。 如果在if 条件内创建指向它的指针,则它是那里的自动变量。函数迭代时不可见。

我可以声明它static,但编译器返回错误error: 'e' undeclared (first use in this function)。例如:在迭代 1 中,指针在 if 语句的一个分支中创建;在迭代 2 中,访问了 if 的另一个分支,我执行了类似 e->etag = "a"; 的操作

如果我声明extern Element * e;,在if 的第二个分支(第一个else if)中会出现同样的错误。

文件输出.c

#include element.h
write_element ( Element * e )
{
    write_to_disk(... e->itag, e->etag);
}

文件解析器.c

#include "element.h"

# some other functions
void parser ( char * f, char * b )
{
    if ( something ) {
        /* Need to access externally defined Element type structure, but it should be visible in all `parser` function */
        Element * e;
        e->itag = ... realloc(...)
        ...

    } else if (..... ) {
        /* Should assume a pointer to Element is already created */
        e->etag = "a";

    } else if ( .... ) {
        /* Should assume a pointer to Element is already created */
        /* and itag, etag and cont have some text */
        write_element( e );
    }

【问题讨论】:

    标签: c static extern linkage


    【解决方案1】:

    代码

    typedef struct Elem {
      char * itag;
      char * cont;
      char * etag;
      struct Elem * previous;
    } Element;
    

    不定义元素。它只告诉编译器它的结构。没有一个元素被定义。

    试试看

    extern Element myElement;
    

    在头文件中。

    在对应的.c文件中放

    Element myElement;

    这将为myElement保留空间

    【讨论】:

    • 主要问题是如何初始化元素,在 if 分支中外部声明,并使其在包含此 if 分支的函数的其他迭代中可访问,它是 if 分支或else if 分支。
    • Element 是数据类型。 myElement 是包含数据的变量。所以要设置itag,例如在你的代码中做myElement.itag=...
    【解决方案2】:

    您应该使用关键字« extern »。例如:

    f.h:

    #ifndef H_LP_F_20120426154230   
    #define H_LP_F_20120426154230 
    
    typedef struct Elem {
        char *itag;
        char *cont;
        char *etag;
        struct Elem *previous;
    } Element;
    
    extern Element myStruct;
    
    #endif
    

    f.c

    #include "f.h"
    
    Element myStruct;
    /* nom I can use myStruct */
    

    【讨论】:

      猜你喜欢
      • 2021-12-24
      • 1970-01-01
      • 2017-10-29
      • 1970-01-01
      • 2013-12-09
      • 2016-11-09
      • 1970-01-01
      • 2018-01-04
      • 1970-01-01
      相关资源
      最近更新 更多