Next: , Previous: Interfacing to C++, Up: Building Mixed Ada & C++ Programs


2.11.2 Linking a Mixed C++ & Ada Program

Usually the linker of the C++ development system must be used to link mixed applications because most C++ systems will resolve elaboration issues (such as calling constructors on global class instances) transparently during the link phase. GNAT has been adapted to ease the use of a foreign linker for the last phase. Three cases can be considered:

  1. Using GNAT and G++ (GNU C++ compiler) from the same GCC installation. The c++ linker can simply be called by using the c++ specific driver called c++. Note that this setup is not very common because it may request recompiling the whole GCC tree from sources and it does not allow to upgrade easily to a new version of one compiler for one of the two languages without taking the risk of destabilizing the other.
              $ c++ -c file1.C
              $ c++ -c file2.C
              $ gnatmake ada_unit -largs file1.o file2.o --LINK=c++
         
  2. Using GNAT and G++ from 2 different GCC installations. If both compilers are on the PATH, the same method can be used. It is important to be aware that environment variables such as C_INCLUDE_PATH, GCC_EXEC_PREFIX, BINUTILS_ROOT or GCC_ROOT will affect both compilers at the same time and thus may make one of the 2 compilers operate improperly if they are set for the other. In particular it is important that the link command has access to the proper gcc library libgcc.a, that is to say the one that is part of the C++ compiler installation. The implicit link command as suggested in the gnatmake command from the former example can be replaced by an explicit link command with full verbosity in order to verify which library is used:
              $ gnatbind ada_unit
              $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
         

    If there is a problem due to interfering environment variables, it can be workaround by using an intermediate script. The following example shows the proper script to use when GNAT has not been installed at its default location and g++ has been installed at its default location:

              $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
              $ cat ./my_script
              #!/bin/sh
              unset BINUTILS_ROOT
              unset GCC_ROOT
              c++ $*
         
  3. Using a non GNU C++ compiler. The same set of command as previously described can be used to insure that the c++ linker is used. Nonetheless, you need to add the path to libgcc explicitely, since some libraries needed by GNAT are located in this directory:
              
              $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
              $ cat ./my_script
              #!/bin/sh
              CC $* `gcc -print-libgcc-file-name`
              
         

    Where CC is the name of the non GNU C++ compiler.