Re: C header files



Robert Dow wrote:

Hi -

Just wondering if anyone could offer advice regarding the use of C header
files in projects, or perhaps a suggestion of a good book or web resource
that might clarify 'best practice'.

At the moment, for example, I have a project where I have a library of
various functions, and some appplications that use those library functions.
What I have done is as follows: each set of related functions has a separate
source file, and a header file that goes with it. An example might make
this clearer:

vectorop.c:

#include <stdlib.h>

<stdlib.h> should be <stddef.h> instead
and it should be in the header file, not the c file,
because you only need size_t for the prototype.

rjdutil.h:

rjdutil.h isn't needed for the shown code.

example.c:

#include <stdlib.h>
#include <stdio.h>
#include "rjdutil.h"

/* BEGIN vectorop.h */

#ifndef INC_VECTOROP_H
#define INC_VECTOROP_H

#include <stddef.h>

void stod(const short *, double *, size_t, double);

#endif

/* END vectorop.h */


/* BEGIN vectorop.c */

#include "vectorop.h"

/* stod: convert a vector of shorts to a vector */
/* of doubles and scale by scale */

void stod(const short *svec,
double *dvec,
size_t len,
double scale)
{
register size_t i;

for (i = 0; i < len; i++) {
dvec[i] = svec[i] * scale;
}
}

/* END vectorop.c */


/* BEGIN example.c */

#include <stdlib.h>
#include <stdio.h>

#include "vectorop.h"

#define BUFLEN 10
#define SCALE 0.5

int main(void) {

register size_t i;
short *pSvec,
j = 0;
double *pDvec;

if( (pSvec = malloc(BUFLEN * sizeof(short))) == NULL) {
(void)fprintf(stderr, "Cannot allocate pSvec");
exit(EXIT_FAILURE);
}

if( (pDvec = malloc(BUFLEN * sizeof(double))) == NULL) {
(void)fprintf(stderr, "Cannot allocate pDvec");
exit(EXIT_FAILURE);
}

for(i=0;i<BUFLEN;i++) {
pSvec[i] = (short)(100 + j);
j++;
}

stod(pSvec, pDvec, BUFLEN, SCALE);

for(i=0;i<BUFLEN;i++) (void)printf("%d %f\n", pSvec[i], pDvec[i]);

free(pSvec);
free(pDvec);

return EXIT_SUCCESS;

}

/* END example.c */



/* BEGIN rjdutil.h */

#ifndef INC_RJDUTIL_H
#define INC_RJDUTIL_H

void dtos(const double *, short *, unsigned int, double);
void ltod(long *, double *, unsigned int, double);

#endif

/* END rjdutil.h */

--
pete
.



Relevant Pages