GCC normal commands

update 20200422 23:30pm


  • -c
    Compile and output relocatable object file xxx.o
  • -Wall
    Output the details of gcc building process.
  • -Werror
    Turns all warnings into erros.
  • -fno-common
    Triggers an error if it encounters multiply-defined global symbols.

calmXia: It is recommended and good for you to use -Werror and -fno-common options in your building scripts(ex: makefile), these can help programmer to avoid some subtle and nasty bugs associated with duplicate symbol names. Details see Section 7.6.1 in《CSAPP》3e .

static libraries

(1) create static libraries:
Ex:

linux> gcc -c x.c y.c
linux> ar rcs libxy.a x.o y.o

(2) compile with static libraries

  • -static
    The -static argument tells the compiler driver(calm: gcc) that the linker should build a fully linked executable object file that can be loaded into memory and run without any further linking at load time.

  • -L. -lvector
    The -lvector argument is a shorthand for libvector.a,
    The -L. argument tells the linker to look for libvector.a in the current directory.

Ex:

linux> gcc -c prog.c
linux> gcc -static -o prog prog.o ./libxy.a

# or

linux> gcc -static -o prog prog.o -L. -lxy

Ref:《CSAPP》3e section 7.6.2: Linking with Static Libraries

shared libraries

  • -shared
    The -shared flag directs the linker to create a shared object file.
  • -fpic
    The -fpic flag directs the compiler to generate position-independent code.

(1) create shared libraries

linux> gcc -shared -fpic libab.so a.c b.c
linux> gcc -o prog prog.c ./libab.so

Ref: 《CSAPP》3e section 7.10: Dynamic Linking with Shared Libraries


(2) compile applications to use(dlopen+dlsym) shared libraries at run time

linux> gcc -rdynamic -o prog prog.c -ldl

then, you can use dlopen+dlsym to load and use some xx.so in prog.c.

  • -rdynamic
    Pass the flag ‘-export-dynamic’ to the ELF linker, on targets that support it. This instructs the linker to add all symbols, not only used ones, to the dynamic symbol table. This option is needed for some uses of dlopen or to allow obtaining backtraces from within a program. Above all, the executable prog its global symbols are also available for symbol resolution.

Ref:

发布了81 篇原创文章 · 获赞 31 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/xiaosaerjt/article/details/105620307
gcc
今日推荐