OK, so what I'm doing right now is creating a function that callocs (I prefer this to malloc) and returns a string, and it will work similar to printf, I'm calling the function alloCpy(), the idea is this:
I have several values that I need in a malloced string, so I call
Code:
myAllocedString = alloCpy("Value 1 is %s, value 2 is %s, and value 3 is %d", str1, str2, num);
To do this I'm using the Variadic Macro, the reason I'm not just using a Variadic Function such as this:
Code:
char* alloCpy(char *format, ...) {}
is because I need to append NULL to the end for the sake of looping through arguments, and I'm understanding it thusfar, but I have a few issues, first of all, I tried defining the Macro in a header file, but when I try to call it I get the error "Undefined reference to alloCpy". Also, to loop through arguments to get string lengths I'm using va_arg(args, char*) which requires all the arguments to be of type char*. Here is my code:
myheader.h:
Code:
#define alloCpy(format, ...) _alloCpy(format, ##__VA_ARGS__, NULL);
char* _alloCpy(char *format, ...);
mycfile.c:
Code:
char* _alloCpy(char *format, ...) {
va_list args;
va_start(args, format);
int args_len = 0;
char *arg;
for(arg = va_arg(args, char*); arg != NULL; arg = va_arg(args, char*))
args_len += strlen(arg);
// Allocated memory will have extra padding because of formatting chars (%s, %d, etc.)
char *dest = calloc(strlen(format) + args_len + 1, sizeof(char));
vsprintf(dest, format, args);
return dest;
}
So, how can I do this to, first of all, make my macro function accessible from other files importing myheader.h, and second, how can I make it accept any type of argument like printf, so that my example above would work?