Example codes:
( Reference from here )
test.c
#include
#include
#include "adio.h"
#include "adstring.h"
int main()
{
char input[21];
char buffer[11];
char buf[11];
const char* str = "hello world!!";
adstring_strcpy(buffer, str, 11);
puts(buffer);
adio_fgets(input, 21, stdin);
puts(input);
adstring_strcpy(buffer, input, 5);
puts(buffer);
int a = 12345;
puts(adstring_itoa(buf, a, 11));
puts(buf);
return 0;
}
adio.h
#ifndef ADVENCE_IO_H
#define ADVENCE_IO_H
#include
char* adio_fgets(char* buf, int num, FILE* fp);
void adio_stdinclean(void);
#endif
adstring.h
#ifndef ADVENCE_STRING_H
#define ADVENCE_STRING_H
char* adstring_strcpy(char* to, const char* from, int num);
char* adstring_itoa(char* to, int from, int num);
#endif
adio.c
#include
#include
char* adio_gets(char* buf, int num, FILE* fp)
{
char* find = 0;
fgets(buf, num, stdin);
if ((find = strrchr(buf, '\n')))
{
*find = '\0′;
}
else
{
while (fgetc(fp) != '\n');
}
return buf;
}
void adio_stdinclean()
{
while (getchar() != '\n');
}
adstring.c
#include
#include
char* adstring_strcpy(char* to, const char* from, int num)
{
int size = num-1;
strncpy(to, from, size);
if (strlen(from) >= size)
{
to[size] = '\0′;
}
return to;
}
char* adstring_itoa(char* to, int from, int num)
{
char tmp[11];
sprintf(tmp, "%d", from);
adstring_strcpy(to, tmp, num);
return to;
}
Make static library , here we assume object files need to be compiler in g++
g++ adio.c adstring.c -Wall -c (this line will come out with adio.o adstring.o)
ar rcs libadlib.a adio.o adstring.o (archieve into libadlib.a file)
gcc test.c -I. -L. -ladlib -o test
Here, there are some errors say that the function with object files is not found.
The reason is that compiler will change c++'s function name while compiling.
In order to tell compiler not to change function name, we can use extern "C"
We can modify adio.c adstring.c into :
adio.c
#include
#include
#ifdef __cplusplus
extern "C" {
#endif
char* adio_gets(char* buf, int num, FILE* fp)
{
char* find = 0;
fgets(buf, num, stdin);
if ((find = strrchr(buf, '\n')))
{
*find = '\0′;
}
else
{
while (fgetc(fp) != '\n');
}
return buf;
}
void adio_stdinclean()
{
while (getchar() != '\n');
}
#ifdef __cplusplus
}
#endif
adstring.c
#include
#include
#ifdef __cplusplus
extern "C" {
#endif
char* adstring_strcpy(char* to, const char* from, int num)
{
int size = num-1;
strncpy(to, from, size);
if (strlen(from) >= size)
{
to[size] = '\0′;
} return to;
}
char* adstring_itoa(char* to, int from, int num)
{
char tmp[11];
sprintf(tmp, "%d", from);
adstring_strcpy(to, tmp, num);
return to;
}
#ifdef __cplusplus
}
#endif
1 comment:
Well said.
Post a Comment