c中的宏定义

时间:2014-05-02 21:14:03

标签: c macros

我被要求实现malloc和free ..我在malloc.c文件中实现了那些包含malloc.h文件的文件,在malloc.h文件中我有这些宏

 #define malloc( x ) mymalloc( x, __FILE__ , __LINE__ )
 #define free( x ) myfree( x, __FILE__ , __LINE__ )
 #define calloc( x,y ) mycalloc( x, y, __FILE__, __LINE__ )

每当我在main函数中使用malloc(10)或其他内容时,它都会显示对mymalloc的未定义引用

2 个答案:

答案 0 :(得分:0)

在Linux(或Windows下的cygwin)下,使用gcc test.c malloc.c -o test,以下内容将起作用(使用./test执行)

<强> test.c的

#include "malloc.h"
int main()
{
   malloc(10);
   return 0;
}

<强> malloc.h所

#define malloc( x ) mymalloc( x, __FILE__ , __LINE__ )
int mymalloc(int x, char *file, int line);

<强> malloc.c

#include <stdio.h>

int mymalloc(int x, char *file, int line)
{
  printf("%s, line %d: %d", file, line, x);
  return 0;
}

编辑:添加mymalloc的原型以避免警告

答案 1 :(得分:0)

注意像

这样的行
p = malloc(10);

由C预处理器扩展为

p = mymalloc(10, "this-file-name.c", /* current line number */);

并且这行无法编译,因为编译器看不到mymalloc()的声明。您需要将以下行添加到mymalloc.h

void *mymalloc(int, const char *, int);
void myfree(void *, cont char *, int);
void *mycalloc(int, int, const char *, int);
相关问题