用C++调用C的库函数(转)
用C++调用C的库函数
C++调用C的库函数时,如果头文件定义得不恰当,可能会出现明明某函数在obj文件中存在,但是却发生链接失败的情况,出现如下错误:
undefined reference to 'xxx'
出现问题的原因是c库函数编译成obj文件时对函数符号的处理和C++不同。因为C++函数支持重载,所以函数符号的处理要更复杂一些,c往往不作修饰。
例如有函数:
/* dofunc.c */
#include <stdio.h>
int dofunc()
{
printf("dofunc\n");
}
使用gcc编译成obj后
gcc -c dofunc.c
#生成 dofunc.o
objdump -x dofunc.o
[ 0](sec -2)(fl 0x00)(ty 0)(scl 103) (nx 1) 0x00000000 dofunc.c
File
[ 2](sec 1)(fl 0x00)(ty 20)(scl 2) (nx 1) 0x00000000 _dofunc
AUX tagndx 0 ttlsiz 0x0 lnnos 0 next 0
[ 4](sec 1)(fl 0x00)(ty 0)(scl 3) (nx 1) 0x00000000 .text
AUX scnlen 0x14 nreloc 2 nlnno 0
[ 6](sec 2)(fl 0x00)(ty 0)(scl 3) (nx 1) 0x00000000 .data
AUX scnlen 0x0 nreloc 0 nlnno 0
[ 8](sec 3)(fl 0x00)(ty 0)(scl 3) (nx 1) 0x00000000 .bss
AUX scnlen 0x0 nreloc 0 nlnno 0
[ 10](sec 4)(fl 0x00)(ty 0)(scl 3) (nx 1) 0x00000000 .rdata
AUX scnlen 0x8 nreloc 0 nlnno 0
[ 12](sec 0)(fl 0x00)(ty 20)(scl 2) (nx 0) 0x00000000 _printf
c的dofunc函数在obj文件里的符号为 _dofunc
再看看使用g++编译后的代码:
g++ -c dofunc.c
objdump -x dofunc.o
SYMBOL TABLE:
[ 0](sec -2)(fl 0x00)(ty &
相关文档:
命令行界面的程序,通常都需要输入命令行参数帮助程序执行。main是最典型的此类应用,main的参数之前都被忽略掉了。
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int count;
printf("The command line has %d arguments:\n", ......
opendir(打开目录)
相关函数
open,readdir,closedir,rewinddir,seekdir,telldir,scandir
表头文件
#include<sys/types.h>
#include<dirent.h>
定义函数
DIR * opendir(const char * name);
函数说明
opendir()用来打开参数name指定的目录,并返回DIR*形态的目录流,和open()类似,接下 ......
#include <stdio.h>
#define LL unsigned long long int
inline LL mod(LL a,LL b)
{
while (a>=b)
a-=b;
return a;
}
//a*b mod c
inline LL MulAndMod(LL a, LL shl_b,LL c)
{
LL val,pre;
pre = mod(a,c);
val = 0;
......
以下代码演示如何用C来模拟多态。gcc版本:3.4.4
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#ifndef class
#define class struct
#endif
#ifndef private
  ......
最近工作不紧,抽空看了下C、C++的指针,发现了一些平时没注意到的指针用法和问题。
1、指针引用
void func1(MYCLASS* &pBuildingElement);
乍一看,怪怪的,看了下解释,细想一下和指针的指针类似:
void func1(MYCLASS** pBuildingElement);
看下面的例子:
...
MyClass* p = new MyClass;
func1(p);
......