下面是我的一个例子:
一、头文件
// sysinfo.h
#ifndef SYSINFO_H_
#define SYSINFO_H_
#include
#include
#include
#include
#include
#include
#include
using namespace std;
using std::string;
#define MAX_NAMESIZE 65
#define MAX_DATESIZE 30
#define MAX_TIMEZONESIZE 6
int getSysinfo(string &datetime, string &hostname, string &domainname);
int setSysinfo(char** data);
#endif /* SYSINFO_H_ */
二 、.cpp文件
sysinfo.cpp
#include "sysinfo.h"
/* get datatime, hostname and domainname
* return -1: get data error;
* return 0: success
* */
int getSysinfo(string &datetime, string &hostname, string &domainname)
{
char tmp[MAX_DATESIZE] = { 0 };
char date[MAX_DATESIZE] = { 0 };
char host_name[MAX_NAMESIZE] = { 0 };
char domain_name[MAX_NAMESIZE] = { 0 };
time_t nowtime;
struct tm local_timeinfo, *timeinfo;
time(&nowtime);
timeinfo = localtime(&nowtime);
local_timeinfo = *timeinfo;
/* get year, month, day, hour, minute, second */
if (strftime(tmp, sizeof(tmp), "%Y/%m/%d %X",&local_timeinfo) == 0)
{
return -1;
}
/* get time zone */
timeinfo = gmtime ( &nowtime );
int timezone = local_timeinfo.tm_hour - timeinfo->tm_hour;
if (timezone > 0)
{
sprintf(date, "%s GMT+%d", tmp, timezone);
datetime = date;
}
else if (timezone < 0)
{
sprintf(date, "%s GMT%d", tmp, timezone);
datetime = date;
}
/* get hostname */
if (gethostname(host_name, sizeof(host_name)) == -1)
{
return -1;
}
hostname = host_name;
/* get domainname */
if (getdomainname(domain_name, sizeof(domain_name)) == -1)
{
return -1;
}
domainname = domain_name;
return 0;
}
三、 编译生成.so
g++ sysinfo.cpp -fPIC -shared -o libsysinfo.so
注意 .so文件的命名形式 用lib****.so
四、 拷贝.so到lib文件夹,拷贝.h文件到include文件夹
cp sysinfo.h /usr/include/
cp libsysinfo.so /usr/lib //如果是64位系统应该拷到 /usr/lib64 文件中
执行: ldconfig -p
五、 使用示例
// main.cpp
#include
#include
#include
#include
#include
#include
using namespace std;
int main(int argc, char *argv[])
{
string date, hostname, domainname;
char* data[9];
for (int i = 0; i < 9; i++)
{
data[i] = new char[20];
}
getSysinfo(date, hostname, domainname);
cout << "getsysinfo: " << date << hostname << domainname << endl;
return 0;
}
编译: g++ -o main main.cpp -lsysinfo
运行: ./main
即可成功。