views:

54

answers:

2

How can I create a macro for getting the library name a class is compiled into? Is there some way of getting this information from make?

Essentially I'd like to do something like:

  #  define LIBRARY_NAME (get info from make maybe?)
  ...
  #  ifdef LIBRARY_NAME
        static const char* s_lib_name = STRINGIZE(LIBRARY_NAME);

Thank you!

+3  A: 

g++ allows you to use -DMACRO_NAME=MACRO_VALUE to supply macro values on the command line. Presumably other compilers have similar features.

This is equivalent to having

#define MACRO_NAME MACRO_VALUE

at the top of each file being processed.

Leaving out the =MACRO_VALUE part is equivalent to a plain #define MACRO_NAME.

So now all you have to do is get make to keep track of the final destination for each file you're compiling (which may or may not be trivial, depends on exactly what you're doing...).


You might also look into the # stringization and ## tokenization operators in the c preprocessor. They could save you a little work here...

dmckee
A: 

The compiler cannot know whether or not the object file it is creating will be archived in a library or linked into an executable - that is a separate and independent process, so there is no practical way to achieve this for static libraries; especially since a single object file might be archived to multiple libraries, and the library's name is arbitrary, you could change the name of the file and it would make no difference. You could even extarct an object form one library, and add it to another completely different one.

There is a predefined macro __FILE__ which resolves to the filename of the source being compiled. But I am not sure how that would help you. That would tell you the sourcefile (and implicitly the object file), but not the library.

There may be some way this could be done for DLLs or shared libraries since these are loaded at run-time so the library filename must implicitly be known at runtime.

Clifford