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

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

错误

我编译了共享库没有问题,但是当我尝试编译使用此库的可执行文件时,我有以下错误:iface / libtestlib.so:未定义引用’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 / LIB1:
alib.cpp和alib.h

$PROJECT_DIR / IFACE:
iface.cpp,iface.h,libtestlib.so和所有由cmake生成的.

$PROJECT_DIR /主:
main.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

最佳答案 感谢袁的评论,我发现了这个问题.我需要将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 )
点赞