Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import a variable into a C program from a Makefile

Tags:

c

makefile

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. :-)

like image 371
sud03r Avatar asked Jan 21 '26 04:01

sud03r


2 Answers

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);
like image 67
qrdl Avatar answered Jan 22 '26 18:01

qrdl


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);
like image 34
Jason Coco Avatar answered Jan 22 '26 18:01

Jason Coco