ninjagn

gn+ninja link failed under ubuntu but workable on Arch Linux


At first, the official gn example is workable under ubuntu (gcc 7.3.0).

git clone --depth=1 https://gn.googlesource.com/gn
cp -a gn/tools/gn/example .
cd example
gn gen out
ninja -C out

I have modified the hello.cc as

#include <stdio.h>

#include "hello_shared.h"
#include "hello_static.h"

#include <readline/readline.h>  // add this line
#include <readline/history.h>   // add this line

int main(int argc, char* argv[]) {
        // begin of test code
        int i;

        for (i=0; i<3; i++) {
                char *p=readline("try:");
                printf("%d: %s\n", i, p);
        }
        // end of test code
  printf("%s, %s\n", GetStaticText(), GetSharedText());
  return 0;
}

Now the ninja -C out shows the following error messages I

ninja: Entering directory `out'
[1/1] LINK hello
FAILED: hello
g++ -Wl,-rpath=\$ORIGIN/ -Wl,-rpath-link= -o hello -Wl,--start-group @hello.rsp  -Wl,--end-group
obj/hello.hello.o: In function `main':
hello.cc:(.text+0x25): undefined reference to `readline'
collect2: error: ld returned 1 exit status
ninja: build stopped: subcommand failed.

And the g++ hello.cc hello_static.cc hello_shared.cc -o hello -l readline workable, that means readline library exist and workable.

The same test process workable under Arch Linux (gcc 8.2.1)

The ubuntu environment is a docker container as Dockerfile like

FROM ubuntu
RUN apt update -y
RUN apt upgrade -y
RUN apt install -y build-essential g++ unzip ninja-build pkg-config \
 libreadline-dev

Solution

  • For newer gcc/g++ 8.x or gcc/g++ 4.x(CentOS6), the ldflags options could be put either before or after the object files. But the gcc/g++ 7.x can only be put after the object files.

    Change example/build/toolchain/BUILD.gn from

    tool("link") {
      ...
      command = "g++ {{ldflags}} -o $outfile -Wl,--start-group @$rspfile {{solibs}} -Wl,--end- group {{libs}}"
      ...
    }
    

    to

    tool("link") {
      ...
      command = "g++ -o $outfile -Wl,--start-group @$rspfile {{solibs}} -Wl,--end- group {{libs}} {{ldflags}}"
      ...
    }