尝试编译使用共享库的C ++程序时出错

时间:2016-05-08 12:41:06

标签: c++ linker cmake linker-errors

我正在尝试编译一个使用C ++的共享库(也是由我开发)的示例程序,其名称为libtestlib.so

错误

我编译了共享库没有问题,但是当我尝试编译使用此库的可执行文件时,我遇到以下错误:iface/libtestlib.so: undefined reference to 'ALIB::function()'

我做了什么

我做了以下事情:

C ++库($project_dir/lib1中的文件):

// HEADER
#ifndef ALIB_H
#define ALIB_H

namespace ALIB{
    int function();
}

#endif
-------------------------------------------
// SOURCE
#include "alib.h"

using namespace ALIB;

int ALIB::function(){
    return 101;
}

C ++库的C接口($project_dir/iface中的文件)

// HEADER
#ifndef IFACE_H
#define IFACE_H

#include "alib.h"

extern "C"{
    int IFACE_function();
}

#endif
--------------------------------
// SOURCE
#include "iface.h"

int IFACE_function(){
    return ALIB::function();
}
--------------------------------------------------------
// CMakeLists used to build the library:
cmake_minimum_required(VERSION 2.8)
PROJECT( testlib )
include_directories( ../lib1 )
add_library( testlib SHARED iface.cpp )

使用该库的可执行文件($project_dir/main中的文件):

// SOURCE
#include "iface.h"
#include <iostream>

using namespace std;

int main(){
    cout << IFACE_function() << endl;
}

-------------------------------------

// CMakeLists used to build the executable (file in `$project_dir`):
cmake_minimum_required(VERSION 2.8)
PROJECT( testlib )
find_library( LIB NAMES testlib PATHS ./iface )
include_directories( ./lib1 ./iface )
add_executable( testlib ./main/main.cpp )
target_link_libraries( testlib ${LIB} )

生成的文件

$project_dir: 全部由cmake生成。 (CmakeLists.txt,CMakeCache,cmake_install.cmake,MakeFile)

$project_dir/lib1alib.cppalib.h

$project_dir/ifaceiface.cpp, iface.h, libtestlib.so和所有由cmake生成的。

$project_dir/mainmain.cpp

作为树:

$project_dir
├── CMakeCache.txt
├── CMakeFiles
│   ├── ...
├── cmake_install.cmake
├── CMakeLists.txt
├── CMakeLists.txt~
├── iface
│   ├── CMakeCache.txt
│   ├── CMakeFiles
│   │   ├── ...
│   ├── cmake_install.cmake
│   ├── CMakeLists.txt
│   ├── CMakeLists.txt~
│   ├── iface.cpp
│   ├── iface.h
│   ├── libtestlib.so
│   └── Makefile
├── lib1
│   ├── alib.cpp
│   └── alib.h
├── main
│   └── main.cpp
└── Makefile

1 个答案:

答案 0 :(得分:1)

感谢袁的评论,我发现了这个问题。我需要将alib.cpp文件添加到CMakeLists.txt,这样:

// CMakeLists used to build the library:
cmake_minimum_required(VERSION 2.8)
PROJECT( testlib )
include_directories( ../lib1 )
add_library( testlib SHARED iface.cpp ../lib1/alib.cpp )