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:


#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 isn't needed for the shown code.


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

/* BEGIN vectorop.h */


#include <stddef.h>

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


/* 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");

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

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

stod(pSvec, pDvec, BUFLEN, SCALE);

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




/* END example.c */

/* BEGIN rjdutil.h */


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


/* END rjdutil.h */


Relevant Pages

  • Re: memory
    ... >statement caused a corruption of the free memory pool or allocated ... When I see the function that has a bound error I use ... struct {union header *ptr; ... void* malloc_m ...
  • Re: LNK2005...
    ... every file that includes your header is also ... extern int myvarible; ... > afx_msg void OnRecordEnd(); ... > DWORD dwInstance, ...
  • RE: Two Row Headers in DataGridView
    ... header) to all the cells in that column?. ... Rectangle r1 = ... void dataGridView1_Paint(object sender, PaintEventArgs e) ...
  • [tip:perf/core] perf tools: Merge content into
    ... perf tools: ... But current previous versions handle the header size using its ... char *buf; ... static void do_write ...
  • [RFC][PATCH] perf tools: Merge content into
    ... But previous versions handle the header size using its ... static void do_write ... u64 event_offset; ... char buf; ...