1

I am new to C. I am coding in Ubuntu 12.04. I've just faced this problem and solved it using the solution provided for that question(using -lncurses flag while compiling with gcc).

My questions are,

  1. Do we have to explicitly mention every library used in our program as a flag to gcc so that it can link to object file ?

  2. If we have to do it why to write header files on the top our program like #include<stdio.h> or#include` ?

  3. Do we have to maintain some order in which this library flags are written in gcc command. Because of a statement in this answer says that order matters? What decides the order of flags ?

Thanks in advance.

Community
  • 1
  • 1
aravind ramesh
  • 307
  • 2
  • 15

1 Answers1

1
  1. Usually, yes. Some libraries work with a script called pkg-config that tells you how to link; e.g. pkg-config --libs libzip will give the linker flags for libzip, which are -lzip -lz.

  2. Headers contain declarations of functions, definitions of data structures, and other things that are relevant at for the compiler, but no information for the linker. This is a bit of a historic accident; it was fixed in the Plan 9 C compiler and I believe also in Microsoft's compiler, but not in common Unix/Linux compilers.

    Mind you, headers and libraries are not in one-to-one correspondence. E.g. some libraries are "header-only", and some libraries including libc have many headers. In other cases, multiple versions of a library can be available (a common version, a debugging version, an optimized version for some processor, ...), all with the same header.

  3. I believe this depends on the GCC version, but I've never figured out which versions require strict ordering and which don't. The safe bet is to link with libraries in reverse dependency order; so if libfoo uses libbar, link with libfoo first, then libbar. The aforementioned pkg-config takes care of this as well for the libraries that support it.

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
  • So we will have to find the flags of library using `pkg-config` ? – aravind ramesh Aug 22 '13 at 13:49
  • @aravindramesh: if supported. Otherwise, check the library's documentation. – Fred Foo Aug 22 '13 at 13:50
  • for 2) As we are linking the `lib` in gcc command. Can we omit headers for that library ?. I tried for ncurses and it worked ? is this a exception or a standard behaviour ? – aravind ramesh Aug 22 '13 at 13:54
  • @aravindramesh: impossible to tell without seeing code. In general, if the documentation for a library tells you to `#include` a header, then `#include` that header. Otherwise, your code might compile today but not after the next upgrade. – Fred Foo Aug 22 '13 at 14:20