程序的目的是,提供C或C++的接口,判断一个字符串是否为回文。
pal.h
int is_palindrome (char * word);
pal.hpp
class palindrome {
public:
palindrome ();
bool is_palindrome (char * word);
};
pal.cpp
#include "pal.hpp"
#include <string.h>
using namespace std;
extern "C" int is_palindrome (char * word)
{
int ret = 1;
char * p = word;
int len = strlen (word);
char * q = &word[len-1];
for (int i = 0 ; i < len ; i++, p++, q--)
{
if (*p != *q)
{
ret = 0;
}
}
return ret;
}
bool palindrome::is_palindrome (char * word)
{
bool ret = true;
char * p = word;
int len = strlen (word);
char * q = &word[len-1];
for (int i = 0 ; i < len ; i++, p++, q--)
{
if (*p != *q)
{
ret = false;
}
}
return ret;
}
编译出 pal.o:
# g++ -fPIC pal.cpp
# ls
pal.cpp pal.h pal.o
生成 libpal.so:
# ld -shared pal.o -o libpal.so
# ls
libpal.so pal.cpp pal.h pal.o
# sudo mv libpal.so /usr/lib64
# sudo ldconfig
# sudo ldconfig -p | grep libpal
libpal.so (libc6,x86-64) => /lib64/libpal.so
C++ 程序
接下来,我们创建一个 main.cpp 来调用这个共享库中的函数:
main.cpp
#include "pal.hpp"
#include <iostream>
using namespace std;
int main()
{
palindrome a;
while (1)
{
char buffer[64] = {0};
cin >> buffer;
if (a.is_palindrome(buffer))
{
cout << "Word is a palindrome" << endl;
}
else
{
cout << "Word is not a palindrome" << endl;
}
}
return 0;
}
生成可执行文件 a.out :
# g++ main.cpp -lpal
$ ./a.out
ada
Word is a palindrome
team
Word is not a palindrome
C 程序
main.c
#include "pal.h"
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main()
{
while (1)
{
char buffer[64] = {0};
read(STDIN_FILENO, buffer, 60);
int len = strlen(buffer);
buffer[len-1] = 0;
if (is_palindrome(buffer))
{
printf ("Word is a palindrome\n");
}
else
{
printf ("Word is not a palindrome\n");
}
}
return 0;
}
生成可执行文件 b.out :
# gcc main.c -lpal -o b.out
$ ./b.out
ada
Word is a palindrome
team
Word is not a palindrome
参考文章链接
1 Creating a Shared Library
2 Installing and Accessing Shared Libraries
3 C++ Dynamic Shared Library on Linux
网友评论