Posts Tagged ‘linux’
远比想象中的简单,其实就是两点:1.为C++风格的接口做一个wrapper,利用extern “C”。2.编译选项中加上-lstdc++ 比如说有一个库是这样的: ClassA.h: class A { private: int x; public: A(int _x); getResult(int ax); }; 编译成ClassA.o,然后打包成libClassA.a 为了能用c调用这libClassA,需要对它作一个Wrapper: CClassA.h #ifdef __cplusplus extern "C" { #endif int A_init(int); int A_getResult(int); #ifdef __cplusplus } #endif 需要注意的是,CClassA.h里,不能include C++的头文件,你知道的…… CClassA.c里面,wrapper函数的实现: #include "ClassA.h" A * a = NULL; int A_init(int _x) { a = new A(_x); } int A_getResult(int ax) [...]
大家都知道,linux底下做程序性能优化,gprof是个简单有效的工具,可是我今天在用gprof跑一个多线程的模块时发现奇怪的现象:统计出来的总用时跟实际时间非常不一致,而且CPU时间消耗的热点也非常不符合实际情况。仔细一看,理论上应该是被很多次调用的一个函数,总消耗时间竟然是 0s,这个函数会被很多线程调用到,莫非是gprof不支持多线程? 这种时候还是搜索引擎管用,马上找到了问题关键:gprof依赖于ITIMER_PROF信号来计时,而linux下的多线程中只有主线程才能响应这个信号,所以就导致子线程中的函数调用耗时都为0. 解决方案:网上的牛人已经给了最佳解决方案,对pthread_create做一个wrapper。(http://sam.zoy.org/writings/programming/gprof.html) /* gprof-helper.c — preload library to profile pthread-enabled programs * * Authors: Sam Hocevar <sam at zoy dot org> * Daniel Jönsson <danieljo at fagotten dot org> * * This program is free software; you can redistribute it and/or * modify it under the terms of the Do What The Fuck [...]
话说好不容易升级完了一个模块,经历了千辛万苦终于可以上线了,可是刚上线就core dump了,巨汗。 查了一下,这个模块是在启动过程中就core掉了,SIGSEGV,问题竟然是因为这么一句: sprintf(hostname, "%s", getenv("HOSTNAME")); 厄,不管怎么说,回头看来这行代码是有很多问题的,但是现在只列出两个: 1. sprintf有溢出的危险,用snprintf才是王道。(真不知道当时自己是怎么想的) 2. getenv(“HOSTNAME”)是有可能返回NULL的,尽管sprintf非常恰当的处理了空指针的情况(实际上,它会打出一个”(null)”),但是将一个函数的返回值直接作为参数传入还是不安全的。 问题的关键就在getenv这个函数: NAME getenv – get an environment variable SYNOPSIS #include <stdlib.h> char *getenv(const char *name); DESCRIPTION The getenv() function searches the environment list for a string that matches the string pointed to by name. The strings are of the form name = value. RETURN [...]
