假定以下源文件的路径为: /users/kwarph/say_hello/src
假定共享库存放的路径为: /users/kwarph/say_hello/bin
/*
* cpp02.h
*
*/
#ifndef CPP02_H_
#define CPP02_H_
#include <string>
class cpp02 {
public:
cpp02();
cpp02(const std::string& name);
void hello() const;
std::string who() const;
void who(std::string& name);
private:
std::string who_;
};
#endif /* CPP02_H_ */
/*
* cpp02.cpp
*
*/
#include <iostream>
#include "cpp02.h"
cpp02::cpp02() {
}
cpp02::cpp02(const std::string& name) :
who_(name) {
}
void cpp02::hello() const {
std::cout << "Welcome to XuanYuan Open Lab, " << (who_ == "" ? "my friend"
: who_) << "!\n";
}
std::string cpp02::who() const {
return who_;
}
void cpp02::who(std::string& name) {
who_ = name;
}
$ cd /users/kwarph/say_hello/bin
$ g++ -O0 -g3 -Wall -c -o"cpp02.o" "../src/cpp02.cpp" #注意:是Debug版本,开启了-g3选项
$ g++ -shared -o"libsay_hello.so" cpp02.o
假定测试代码的路径:/users/kwarph/test_say_hello/src
假定测试程序的路径:/users/kwarph/test_say_hello/bin
/*
* cpp03.cpp
*
*/
#include "cpp02.h"
int main() {
cpp02 c("bill joy");
c.hello();
}
$ cd /users/kwarph/test_say_hello/bin $ g++ -I"/users/kwarph/say_hello/src" -O0 -g3 -Wall -c -o"cpp03.o" "../src/cpp03.cpp" # -I 指定所需的头文件所在路径 $ g++ -L"/users/kwarph/say_hello/bin" -o"cpp03" cpp03.o -lsay_hello # -L 指定共享库所在的路径
$ ./cpp03
注意:如上方式执行,会报如下错误:
/users/kwarph/test_say_hello/bin/cpp03: error while loading shared libraries: libsay_hello.so: cannot open shared object file: No such file or directory
说明cpp03在运行期无法找到动态库: libsay_hello.so,这个问题可以通过以下几个途径解决:
重新执行cpp03
$ export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/users/kwarph/say_hello/bin $ ./cpp03 $ Welcome to XuanYuan Open Lab, bill joy!