How to make c/c++ dynamic libarary

How to compile a project having dynamic libarary;

============== c ===============

[qa@qa133 edu-gdb]$ mkdir HelloWorld
[qa@qa133 HelloWorld]$ vi HelloWorld.c
#include <stdio.h>
void sayHello(void){

printf("Hello, World!\n");
}

[qa@qa133 HelloWorld]$ vi HelloWolrd.h
void sayHello(void);


[qa@qa133 HelloWorld]$ vi Main.c
#include "HelloWorld.h"

int main(void){

sayHello();
return 0;
}

[qa@qa133 HelloWorld]$ gcc -c HelloWorld.c -o HelloWorld.o
[qa@qa133 HelloWorld]$ gcc -c Main.c -o Main.o
[qa@qa133 HelloWorld]$ gcc -shared -Wall -fPIC HelloWorld.o -o libHelloWorld.so
[qa@qa133 HelloWorld]$ export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/u2/testing/users/xiyang_/edu-gdb/HelloWorld
[qa@qa133 HelloWorld]$ cc -o Main Main.o -lHelloWorld -B /u2/testing/users/xiyang_/edu-gdb/HelloWorld
[qa@qa133 HelloWorld]$ ls
HelloWorld.c HelloWorld.o Main Main.o
HelloWorld.h libHelloWorld.so Main.c
[qa@qa133 HelloWorld]$ ./Main
Hello, World!
[qa@qa133 HelloWorld]$ ldd Main
linux-gate.so.1 => (0xffffe000)
libHelloWorld.so (0xb7f34000)
libc.so.6 => /lib/libc.so.6 (0xb7e03000)
/lib/ld-linux.so.2 (0xb7f37000)


============= C++ =============

[qa@qa133 HelloDave]$ vi HelloDave.C
NOTE:
If you are on a unix machine, save the file with the filename hello.C (make sure it ends with .C, not .c, If you are on a Windows machine, save the file with the filename hello.cpp.
[qa@qa133 HelloDave]$ g++ HelloDave.C -o HelloDave
#include <iostream>
using namespace std;
int main(){

cout << "Hello, World!" << endl;

return 0;

}

[qa@qa133 HelloDave]$ ./HelloDave
Hello, World!
NOTE:
Both
#include<iostream.h>
or
#include<iostream>
using namespace std;
are OK.
#include<iostream.h> generally used in c
#include<iostream>
using namespace std; generally used in C++


=========== GDB ===============

#include <stdio.h>

static char buff [256];
static char* string;
int main ()
{
   printf ("Please input a string: ");
   gets (string);  
   printf ("\nYour string is: %s\n", string);
}


  上面这个程序非常简单,其目的是接受用户的输入,然后将用户的输入打印出来。该程序使用了一个未经过初始化的字符串地址 string,因此,编译并运行之后,将出现 Segment Fault 错误:
$ gcc -o bugging -g bugging.c
$ ./bugging
Please input a string: asfd
Segmentation fault (core dumped)
为了查找该程序中出现的问题,我们利用 gdb,并按如下的步骤进行:
1.运行 gdb bugging 命令,装入 bugging 可执行文件;
2.执行装入的 bugging 命令 run;
3.使用 where 命令查看程序出错的地方;
4.利用 list 命令查看调用 gets 函数附近的代码;
5.唯一能够导致 gets 函数出错的因素就是变量 string。用print命令查看 string 的值;
6.在 gdb 中,我们可以直接修改变量的值,只要将 string 取一个合法的指针值就可以了,为此,我们在第8行处设置断点 break 8;
7.程序重新运行到第 8行处停止,这时,我们可以用 set variable 命令修改 string 的取值;
8.然后继续运行,将看到正确的程序运行结果
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值