Hi All..
I'm writting my own replacements for the memory allocation/deallocation routines
malloc() and free().In that file i'm using some variable names..
So after getting the header file, how can i use those previous variable names which i declared in mymalloc programme in any programme.
In my main programme i include <mymalloc.h> and do some variable declarations. but gcc said that some of those variable names already in the mymalloc..
So please help me to avoid this problem :S

Recommended Answers

All 2 Replies

When writing a library you need to take care to only make the names that should be visible to client code extern; the rest should be static for file visibility. Names that are extern should be designed to avoid clashing with client code and other libraries as well. Finally, any objects and functions should only be declared in your header, then defined in a separate definition file to avoid multiple definitions if the header is included more than once. For example:

/* mymalloc.h */
#ifndef MYMALLOC_H
#define MYMALLOC_H

#include <stddef.h>

/* Declaration only for variable */
extern int mymalloc_use_freelist;

/* Declarations only */
extern void *mymalloc(size_t bytes);
extern void myfree(void *p);

#endif
/* mymalloc.c */
#include <mymalloc.h>
#include <mylist.h>

/* Not visible to the outside */
static mylist *freelist = NULL;

/* Definition for extern variable */
int mymalloc_use_freelist = 0;

/* Not visible to the outside, internal helper only */
static void *more_core(size_t bytes)
{
    /* ... */
}

/* extern function declarations */
void *mymalloc(size_t bytes)
{
    /* ... */
}

void myfree(void *p)
{
    /* ... */
}

Macro names can be an issue, but if they're intended for internal use only, you can #undef them at the end of the file.

Great!! It works perfectly..
Thankx Narue..:)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.