Mikhail T. Mikhail T. - 1 year ago 60
C Question

Is there a way to detect, a C-file is compiled directly into an executable?

I'd like to include a testing

-function in some of the C-files -- to allow them to be compiled into standalone little programs to independently test various functions.

But I don't want these multiple
-functions included in the real (big) executable/library.

Obviously, I can use my own
, such as
, but it occurred to me, that clang may already be telling me on its own. Somehow...

So, is there any way for the compiled code to detect, when it is compiled directly into an executable vs. when an object-file is being produced (with the

The solution needn't be universal -- I'm quite certain, a universal one does not exist -- my main compiler is clang...

Answer Source

I don't see a better solution than -DINCLUDE_TEST_MAIN. Probably you could create some fancy command line that would strip main out of the object file if you don't need it, but I think the -D thing is the best way to go.

I don't really get what you mean with »but it occurred to me, that clang may already be telling me on its own. Somehow...« - if you fear a name clash, than just take a name, clang will definitively not use, like -DMIKHAIL_T_INCLUDE_TEST_MAIN; if this is not what you meant, then you should clarify that point.

Or, besides stuff.c, you could create stuff.main.c and test compile like so:

gcc stuff.c stuff.main.c -o stuff.test

(effectively moving main out of the file.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download