Re: Linking multiple languages

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Andrew Haley wrote:
On 08/31/2013 03:10 AM, NightStrike wrote:
If I compile c++ code, I am supposed to use g++.  This automatically
does some magic that calling just Gcc would not do. The same with
Fortran code and gfortran.  So my question is which frontend should I
use to link if I have object files from both c++ as well as Fortran,
c, and maybe another language still?

You'll probably use gcc but explicitly link in each language's support
library.

Andrew.




You can really do it in whatever way you want. If you have an application with mixed src code, you could compile it as FORTRAN and link to the c library, or compile as c and link to the FORTRAN library. Whether you compile as c or c++ doesn't make any real difference.

You need separate compile rules for each compiler (c, c++, FORTRAN). These will compile the objects from your mixed src. Then you need a build rule the will link the objects, including one of the libraries.

Here is a sample, where your src is,
.src/main.cpp
.src/MY_FUNCTION1.FOR
.src/my_function2.cpp
.src/my_function2.c

SOURCELOC = ./src
BDIR = ./bld

# mixed app objects objects
MIXED_OBJS = \
         $(BDIR)/main.o \
         $(BDIR)/MY_FUNCTION1.o \
         $(BDIR)/my_function2.o \
         $(BDIR)/my_function3.o

# build my_app, build as gfortran and link to c library
$(BDIR)/my_mixed_app.exe: $(MIXED_OBJS)
	gfortran -o $@ $(MIXED_OBJS) -lstdc++

# compile src gfortran objects with FORTRAN preprocessor
$(BDIR)/%.o: $(SOURCELOC)/%.FOR
	gfortran -c -o $@ $<

# compile src c++ objects
$(BDIR)/%.o: $(SOURCELOC)/%.cpp
	g++ -c -o $@ $<

# compile src c objects
$(BDIR)/%.o: $(SOURCELOC)/%.c
	gcc -c -o $@ $<

You should also be able to compile your .c files as g++, but since you are using the file extension to indicate the compiler, you will need a rule that lets make know to use g++ for .c.

# compile src c objects
$(BDIR)/%.o: $(SOURCELOC)/%.c
	g++ -c -o $@ $<

You could do the same thing with a link rule to build as g++ and link to the fortran library.

# build my_app, build as g++ and link to fortran library
$(BDIR)/my_mixed_app.exe: $(MIXED_OBJS)
	g++ -o $@ $(MIXED_OBJS) -lgfortran

If I remember right, one of the reasons to build as FORTRAN and link to the c library is that many systems may not have a FORTRAN runtime library installed, but most will have a c library somewhere. I'm not 100% sure about that, so perhaps someone else will comment.

As with everything else, start with a simple program and get it working.

LMH

















[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux