两个 gcc 的问题及gprof的用法

40 views
Skip to first unread message

周立发

unread,
Oct 9, 2009, 5:40:29 AM10/9/09
to china-li...@googlegroups.com
2009/10/9 王虎 <ghost...@gmail.com>
周老师,您好:
    请教两个 GCC 的问题:
    1、工程目录如下:

proj /
   |---- src/foo.cpp
   |---- include/ foo.h common.h
   |---- lib/ bar.o

这里只是生成了一个.o的文件,最好再用ar命令创建一个libbar.a或libbar.so之类的库文件。
现在假设已经 是lib/libbar.a
现在要用 GCC 编译 foo.cpp,要怎么弄?假设当前目录在 src 目录下,要用到 foo.h common.h bar.o

gcc -o foo.o -Idir=../include 那个库文件的路径怎么指定?

gcc -o foo.o -I../include -L../lib -lbar
即可
-L指定库的路径,-l指定库的名称,不过要注意对于一个库xx,对应的库文件是libxx.a或libxx.so,即有前缀和后缀规定的。

    2、gcc 有一个 -p 和 -pg 的选项,说是生成 profile 文件的,给分析程序 prof 和 gprof 使用的。但我 google 了一下,不见 prof 和 gprof 的信息。还请周老师帮我讲解一下。

周老师的那个视频我还没有看完,不知道里面有没有讲到 GCC 的使用,晚上回家了我再看看。打算这个周末把 GCC 的使用,好好学习一下。这点周老师可以给点意见或建议。

谢谢。
prof和gprof这两个tool是用来分析代码的效率的,比如某行代码实际执行时耗时多久之类。不过一般小程序基本分析不出啥,它好象没精确到纳秒级吧
-p这个选项可能因为2.6内核已经不支持prof而没法用了吧,反正我很少用它。
gprof的用法举例:
假设你有这么一份源代码:
/**************源代码test.c开始*************************/
#include <stdio.h>
#include <stdlib.h>

static void a()
{
    printf("\t\t+---call a() function\n");
}

static void c()
{
    printf("\t\t+---call c() function\n");
}

static int b()
{
    printf("\t+--- call b() function\n");
    a();
    c();
    return 0;
}

int main(void)
{
    printf(" main() function()\n");
    b();
}
/**************源代码test.c结束*************************/
用下面的命令编译它将生成可执行程序a.out:
gcc -pg test.c
执行程序a.out,除了正常运行程序外,将生成一个文件gmon.out:
./a.out
现在你可以用命令gprof来分析程序的执行情况了:
gprof a.out gmon.out

不过上面这条命令输出的内容相当多,第一次时认真看一下就行了,以后再用gprof命令可以加参数b来省略一些输出,比如:
gprof -b a.out gmon.out
/**************屏幕输出开始*************************/
zhoulifa@zhoulifa-T23:~$ gprof -b a.out gmon.out
Flat profile:

Each sample counts as 0.01 seconds.
 no time accumulated

  %   cumulative   self              self     total          
 time   seconds   seconds    calls  Ts/call  Ts/call  name   
  0.00      0.00     0.00        1     0.00     0.00  a
  0.00      0.00     0.00        1     0.00     0.00  b
  0.00      0.00     0.00        1     0.00     0.00  c


            Call graph


granularity: each sample hit covers 4 byte(s) no time propagated

index % time    self  children    called     name
                0.00    0.00       1/1           b [2]
[1]      0.0    0.00    0.00       1         a [1]
-----------------------------------------------
                0.00    0.00       1/1           main [9]
[2]      0.0    0.00    0.00       1         b [2]
                0.00    0.00       1/1           c [3]
                0.00    0.00       1/1           a [1]
-----------------------------------------------
                0.00    0.00       1/1           b [2]
[3]      0.0    0.00    0.00       1         c [3]
-----------------------------------------------


Index by function name

   [1] a                       [2] b                       [3] c
/**************屏幕输出结束*************************/

Reply all
Reply to author
Forward
0 new messages