Reputation: 1009
I am making a small, library, and I want to give the user the option to disable the parts they do not require.
lib.h
#ifndef ONLY_BASICS
void complexFunction(void);
#endif
lib.c
#ifndef ONLY_BASICS
void complexFunction(void) {
printf("damn, this is complex alright!\n");
}
#endif
main.c
#define ONLY_BASICS
#include "lib.h"
I have seen this being done in other libraries, what am I missing?
Upvotes: 0
Views: 71
Reputation:
You can make users control the build using the prepossessing macros from the compiler without editing the code. If you use GCC use the switch -D
followed by the macro name. On Microsoft compiler use the /D
option.
For example using GCC, I have:
#include <stdio.h>
int main(int argc, char **argv) {
#ifdef SAYHI
#ifdef CAPITAL
printf("HI\n");
#else
printf("hi\n");
#endif
#elif SAYHELLO
#ifdef CAPITAL
printf("HELLO\n");
#else
printf("hello\n");
#endif
#else
#ifdef CAPITAL
printf("SAY SOMETHING\n");
#else
printf("say something\n");
#endif
#endif
return 0;
}
The user can enable and disable what he want via -DMACRO
without editing the code, example:
$ gcc main.c
$ a.exe
say something
$
$ gcc main.c -DCAPITAL
$ a.exe
SAY SOMETHING
$
$ gcc main.c -DSAYHI -DCAPITAL
$ a.exe
HI
$
$ gcc main.c -DSAYHELLO
$ a.exe
hello
$
Upvotes: 1
Reputation: 224864
It seems you're misunderstanding what a library is and what it's used for. Most (all?) linkers already do what you're trying by not including unreferenced symbols from libraries - it's why with gcc, for instance, you need to put the libraries at the end of the command line after the list of source files that contain references to library functions.
What you're doing seems to be confusing this behaviour with compile-time options for the library itself. In that case, you can use the #ifndef
blocks as you have in lib.h
and lib.c
, but you shouldn't need to do anything in main.c
- the library will already have been built without complexFunction
. You may want to have your library build process generate a header that describes which functionality is available.
Upvotes: 0