Error trying to compile a C ++ program that uses a shared library

I am trying to compile an example program that uses a common library (also developed by me) in C ++, whose name libtestlib.so.

Error

I compiled a shared library without problems, but when I try to compile an executable file that uses this library, I have the following error: iface/libtestlib.so: undefined reference to 'ALIB::function()'

What I've done

I have done the following:

C ++ library (files in $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 interface for C ++ library (files in $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 )

An executable file that uses the library (files in $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} )

Generated files

$project_dir: all generated by cmake. (CmakeLists.txt, CMakeCache, cmake_install.cmake, MakeFile)

$project_dir/lib1: alib.cppandalib.h

$project_dir/iface: iface.cpp, iface.h, libtestlib.so cmake.

$project_dir/main: 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
+4
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 )
+1

All Articles