详解linux中的strings命令简介

2019-10-13 13:19:20丽君

在Linux下搞软件开发的朋友, 几乎没有不知道strings命令的。我们先用man strings来看看:

strings - print the strings of printable characters in files. 

 意思是, 打印文件中可打印的字符。  我来补充一下吧, 这个文件可以是文本文件(test.c), 可执行文件(test),  动态链接库(test.o), 静态链接库(test.a)

脱离代码地长篇大论而不去实际验证, 不是我的风格。 还是搞点代码下菜吧(代码存在test.c中):

#include <stdio.h> 
 
int add(int x, int y) 
{ 
    return x + y; 
} 
 
int main() 
{ 
    int a = 1; 
    int b = 2; 
    int c = add(a, b); 
    printf("oh, my dear, c is %dn", c); 
 
    return 0; 
} 

 我们来看看strings test.c的结果:

[taoge@localhost learn_c]$ strings test.c  
#include <stdio.h> 
int add(int x, int y) 
  return x + y; 
int main() 
  int a = 1; 
  int b = 2; 
  int c = add(a, b); 
  printf("oh, my dear, c is %dn", c); 
  return 0; 
[taoge@localhost learn_c]$  

可以看到, 确实打印出了test.c中的很多字符。

下面, 我们对可执行文件用strings试试, 如下:

[taoge@localhost learn_c]$ gcc test.c  
[taoge@localhost learn_c]$ strings a.out  
/lib/ld-linux.so.2 
=$TsU 
__gmon_start__ 
libc.so.6 
_IO_stdin_used 
printf 
__libc_start_main 
GLIBC_2.0 
PTRh  
[^_] 
oh, my dear, c is %d 
[taoge@localhost learn_c]$  

可以看到, 打印出了a.out中很多字符。

实际上, 如果有目标文件、静态库或动态库, , 也是可以用strings命令进行打印操作的。 我们来看看:

xxx.h文件:

void print(); 

xxx.c文件:

#include <stdio.h> 
#include "xxx.h" 
 
void print() 
{ 
  printf("rainy daysn"); 
} 

然后, 我们来看看怎么制作静态、动态库吧(在后续博文中会继续详细介绍):

[taoge@localhost learn_strings]$ ls 
xxx.c xxx.h 
[taoge@localhost learn_strings]$ gcc -c xxx.c 
[taoge@localhost learn_strings]$ ar rcs libxxx.a xxx.o 
[taoge@localhost learn_strings]$ gcc -shared -fPIC -o libxxx.so xxx.o 
[taoge@localhost learn_strings]$ ls 
libxxx.a libxxx.so xxx.c xxx.h xxx.o 
[taoge@localhost learn_strings]$ strings xxx.o 
rainy days 
[taoge@localhost learn_strings]$ strings libxxx.a 
!<arch> 
/        1437887339 0   0   0    14    ` 
Rprint 
xxx.o/     1437887333 501  502  100664 848    ` 
rainy days 
GCC: (GNU) 4.4.4 20100726 (Red Hat 4.4.4-13) 
.symtab 
.strtab 
.shstrtab 
.rel.text 
.data 
.bss 
.rodata 
.comment 
.note.GNU-stack 
xxx.c 
print 
puts 
[taoge@localhost learn_strings]$  
[taoge@localhost learn_strings]$  
[taoge@localhost learn_strings]$ strings libxxx.so 
__gmon_start__ 
_init 
_fini 
__cxa_finalize 
_Jv_RegisterClasses 
print 
puts 
libc.so.6 
_edata 
__bss_start 
_end 
GLIBC_2.1.3 
GLIBC_2.0 
rainy days 
[taoge@localhost learn_strings]$