g++编译运行c++代码流程以及动态库静态库的创建与使用

一、g++ 编译运行hello world

1编写hello world 代码

#include<iostream>

using namespace std;

int main()
{
  cout << "hello world!" << endl;
  return 0;
}

2 编译及运行

自动生成了a.out可执行的文件

二、程序运行步骤

预处理   .i .ii文件        gcc -E hello.cpp -o hello.i
编译    .s文件            gcc -S hello.cpp -o hello.s
汇编    .o .obj文件       gcc -c hello.cpp -o hello.o
链接    .lib .a文件1234

1 预处理

vim hello.i

  ...上面很长省略了..
  extern wostream wclog;

  static ios_base::Init __ioinit;

}
# 2 "hello.cpp" 2

using namespace std;

int main()
{
  cout << "hello world!" << endl;
  return 0;
}

2 编译

vim hello.s

      .file  "hello.cpp"
        .local  _ZStL8__ioinit
        .comm  _ZStL8__ioinit,1,1
        .section        .rodata
.LC0:
        .string "hello world!"
        .text
        .globl  main
        .type  main, @function
main:
.LFB971:
        .cfi_startproc
        pushq  %rbp
        .cfi_def_cfa_offset 16
        .cfi_offset 6, -16
        movq    %rsp, %rbp
        .cfi_def_cfa_register 6
        movl    $.LC0, %esi
        movl    $_ZSt4cout, %edi
        call    _ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc
        movl    $_ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_, %esi
        movq    %rax, %rdi

3 汇编

vim hello.o

4 链接

三、多文件编译链接

1 编写add.h add.cpp main.cpp代码

add.h 头文件

#ifndef _ADD_H
#define _ADD_H
extern int add(int a,int b);
//extern 表示函数实现在另一个文件中
#endif

add.cpp 函数实现

int add(int a,int b)
{
  return (a+b);
}

main.cpp main函数

#include<iostream>
#include"add.h"

using namespace std;

int main()
{
  int a = 1,b = 2;
  int c = add(a,b);
  cout << a << " + " << b << " = " << c << endl;
  return 0;
}

2 编译运行

四、动态库与静态库

静态库              .a (linux)      .lib (windows)
动态库              .so (linux)  .dll (windows)
gcc时,用-I和-L分别制定库名和库路径

1 静态库的创建与使用

其他地方也要用的话

2 动态函数库的建立与使用

 
  1.首先创建libmyadd.so,即利用add.c这个函数生成动态库
  g++ -share -fPIC -o libmyadd.so add.c
  -share指为共享的,-fPIC表示position independent code位置无关,这是动态库特性
  2.指定动态库生成可执行文件,-L.表示当前文件夹,-lmyadd表示去找libmyadd.so这个动态库文件。
  g++ main.c -L. -lmyadd
  3.直接使用会抱错,找不到动态库,要指定动态库的路径
  ./a.out会报错
  LD_LIBRARY_PATH=. ./a.out指定当前库的路径后在运行就可以了
  4.如果要一直用,可以将.so文件的目录添加到/etc/ld.so.conf里面,然后再执行ldconfig就行了,具体如下面:

如果要永久使用的话该怎么办呢?

例如,我的添加后的ld.so.conf文件就是这个样子:

猜你喜欢

转载自www.linuxidc.com/Linux/2018-10/155023.htm