Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace LD variable in a Makefile to link C objects

Tags:

c

makefile

ld

I'm writing a Makefile for C. I want be able to specify different programs for compilation and linking via environmental variables. However, I want it works without any additional variables too. I was trying to link with ld. However, the default doesn't link with standard C library.

The question:
How to link C program with ld or $LD
Is it possible to get appropriate flags from cc?

I cannot use $(CC) in place of $(LD). The LD ?= cc doesn't work too.

I want something like this to be true:
Environment variable CC set to tcc.
Environment variable LD unset.
My Makefile compile using tcc and link using system default linker for C.

Unfortunately, some C compilers are unable to link some libraries. I have this problem with tcc and glfw.

P.S.
Linux user

like image 921
Michas Avatar asked Dec 22 '22 04:12

Michas


2 Answers

The conditional assignment $(LD) ?= cc can not work, since $(LD) is predefined.

If you want to start make without predefined variables, use the option -R:

   > make -p | grep LD
   ... 
   LD = ld
   ...
   > make -p -R | grep LD
   >
like image 194
Matthias Avatar answered Jan 11 '23 23:01

Matthias


Instead of using ld as the linker, use gcc or g++. They add the appropriate command line options for getting libraries and startup code, etc. In other words:

ld -o main main.o

is equivalent to:

gcc -o main main.o

except that gcc adds all the command line parameters when it calls ld.

In other words: LD=gcc.

like image 33
Richard Pennington Avatar answered Jan 12 '23 00:01

Richard Pennington