tags:

views:

79

answers:

3

Hello,

I have create a wrapper for the strncpy function.

I will have to use this in my project which contains many headers and source files (about 20 all together). And this wrapper will be used in most of them.

As the code is very short I am wondering where is the best way to implement this wrapper into my project?

I am thinking this might be useful to have this in a header called utilities.h. And include this header in every source file that needs it?

And maybe any future projects as well?

I am new at C program, so just looking for some good guidance on this issue.

Many thanks,

/* Null terminate a string after coping */
char* strncpy_wrapper(char *dest, const char* source, 
          const size_t dest_size)
{
    strncpy(dest, source, dest_size);
    /* 
     * If the destination is greater than zero terminate with a null.
     */
    if(dest_size > 0)
    {
     dest[dest_size - 1] = '\0';
    }

    return dest;
}
+1  A: 

I think you're headed on the right path. It's quite common to build a library with common functions that can be included where necessary. You'll frequently find them with names such as Helper, Common or as you suggested Utilities.

PaulG
+2  A: 

Your idea of putting it in a utilities.h file is not bad. It's a very common solution. But be sure that there is no more specific way you can categorize this function in your application. As we all know - everything can be labelled miscellaneous which is exactly the meaning of a utilities.h file.

Avihu Turzion
+3  A: 

Using a header is a good idea. I suggest you put a 'guard' around it. Something like:

#ifndef UTILITIES_H
#define UTILITIES_H

//definitions here

#endif //UTILITIES_H
Burkhard
Just a quick question. As this is just one function which is small. Should I have header (utilities.h) with the declaration of my function and a source file (utilities.c) for the definition?
robUK
Usually you put the code in a .c file and the declaration (function signature) in the .h file. This way, you don't need to 'ship' the source code (the compiled code is enough).For a small function it is odd, but when the projects grows, you only compile what is needed and not every source file, which can be a significant increase in compilation time.
Burkhard