Reputation: 3130
I have some class implementation that is going to function as a Lib.
However, I want to include a main
function in that library with a simple driver testing my class. The function main
can therefore be only compiled if I define my compilation target as an executable.
Can this be done via some macro or similar?
I would not like to create a new project nor Makefile, just a simple #ifdef
wrapping the main function would be perfect for this job.
Upvotes: 0
Views: 1278
Reputation: 5917
You can define a macro with the -D
option of GCC. For instance, you can define a macro _RELEASE
with option -D_RELEASE
and wraps as the following:
#ifdef _RELEASE
// Release main
int main()
{
// ...
}
#else
// Another main
int main()
{
// ...
}
#endif
You can compile a main or another by adding -D_RELEASE
to your compilation line:
gcc main.c -D_RELEASE [other flags] # compile with release main
gcc main.c [other flags] # compile with other main
This is an example for a main
function, but of course it can be implemented for any function in a library.
Upvotes: 2
Reputation: 180205
No, this can't be done by a macro. Wrong phase of compilation. Both C and C++ have 3 relevant steps: Per Translation Unit, the preprocessor and the compiler itself are run. Finally, the TU's are linked together by the linker.
While preprocessing or compiling an individual TU, you can't know what other TU's might contain, or what you will be linked into. In fact, it's quite possible that the makefile defines rules either way. E.g. file1.obj might go both into A.LIB and A.EXE.
Upvotes: 0