我如何在其他文件中使用变量,函数和结构?

时间:2011-11-21 09:28:12

标签: c

timer.c我有

typedef struct Timer {

    int startTicks;
    int pausedTicks;

    int paused;
    int started;

} Timer;

void Init( Timer *t )
{
    t->startTicks = 0;
    t->pausedTicks = 0;
    t->paused = 0;
    t->started = 0;
}

我需要在main.c中做些什么才能在该文件中使用这个结构和函数?

2 个答案:

答案 0 :(得分:3)

通常,.c文件包含定义,而.h文件包含声明。更好的方法是将您的定义保留在标题中:

//timer.h
#ifndef TIMER_H //include guard
#define TIMER_H

typedef struct Timer { //struct declaration

    int startTicks;
    int pausedTicks;

    int paused;
    int started;

} Timer;

void Init( Timer *t ); //method declaration

#endif


//timer.c
#include "timer.h"

void Init( Timer *t ) //method definition
{
    t->startTicks = 0;
    t->pausedTicks = 0;
    t->paused = 0;
    t->started = 0;
}

//main.c
#include "timer.h"  //include declarations
int main()
{
    Timer* t = malloc(sizeof(Timer));
    Init(t);
    free(t);
    return 0;
}

答案 1 :(得分:2)

学习使用header files(通常名为*.h)和#include

了解如何使用多个编译单元编译程序,例如:使用Makefile

不要忘记启用所有警告和调试信息(使用GCC,即gcc -g -Wall,即CFLAGS=-g -Wall中的Makefile