tags:

views:

281

answers:

3

Hi all,

I am required to make some changes in an existing long C source code. There is a top-level Makefile which defines the various compiler options like directory locations of libraries used by the linker.

Something like :

LD_OPTIONS = $(PATH_TO_MYLIB1) $(PATH_TO_MYLIB2)

Now, I am thinking of using dlsym() and dlopen() to use these libraries instead of linking them explicitly. For this, I need the library path.

dlopen( path_to_lib , RTLD_NOW) ;

How can I use the PATH_TO_LIB variable from the Makefile and use it in my program? I thought of using something like "echo with system()". However, it is my expectation that there are better solutions. :-)

+9  A: 

In your makefile you can write

CFLAGS += -DPATH_TO_LIB="somepath/somelib"

so PATH_TO_LIB becomes preprocessor macro you can use in your source like

dlopen(PATH_TO_LIB, RTLD_NOW);
qrdl
+4  A: 

I don't much see the point of your change if your paths are hardcoded anyway, but I digress. You could do something like this:

In the makefile:

CFLAGS = -DMYLIB_1=$(PATH_TO_MYLIB1) -DMYLIB_2=$(PATH_TO_MYLIB2)

Then in your souce:

dlopen(MYLIB_1, RTLD_NOW);
Jason Coco
+2  A: 

Somthing like this perhaps?

In your code

#ifndef PATH_TO_LIB
#error Path to ImportantLib missing
#endif ...

and the compile command might look like:

 cc -DPATH_TO_LIB=\"${PATH_TO_LIB}\"
Nifle
If you're going to do something like that, it's probably better to do a #warning or #error inside the #ifndef block rather than just assigning it to some arbitrary value which will break at runtime (perhaps much later, since we never know when/if/ever this dlopen() will be called)
Jason Coco
You are correct, fixed it.
Nifle
I don't thing the whole "ifndef ... error" thing is really needed. If macro isn't defined, you get "unresolved symbol PATH_TO_LIB" linker error anyway.
qrdl