I met the problem of undefined reference to
when I try to compile the source code with imported variables from an installed C header.
I found quite a few SO posts about undefined reference to
problems, like
- Undefined reference when using a function included in a header file
- undefined reference to c functions in c++ code
- C header issue: #include and “undefined reference”
- undefined reference to function declared in *.h file
I don't find these posts very helpful because I don't directly use gcc
to compile, instead, I use IDE for convenience and edit CMakeLists.txt
to compile the code. So, I wonder how I can edit the CMakeLists to avoid this problem.
Here is the specific problem:
I want to use this C library (libplinkio) in my project. I downloaded the source code and make && make check && sudo make install
it.
Then, I try to compile their example code:
#include <iostream>
#include<stdlib.h>
#include<stdio.h>
#include <plinkio/plinkio.h>
using namespace std;
int main() {
struct pio_file_t plink_file;
snp_t *snp_buffer;
int sample_id;
int locus_id;
if( pio_open( &plink_file, "data/toy" ) != PIO_OK )
{
printf( "Error: Could not open %s\n", "data/toy" );
return EXIT_FAILURE;
}
if( !pio_one_locus_per_row( &plink_file ) )
{
printf( "This script requires that snps are rows and samples columns.\n" );
return EXIT_FAILURE;
}
locus_id = 0;
snp_buffer = (snp_t *) malloc( pio_row_size( &plink_file ) );
while( pio_next_row( &plink_file, snp_buffer ) == PIO_OK )
{
for( sample_id = 0; sample_id < pio_num_samples( &plink_file ); sample_id++)
{
struct pio_sample_t *sample = pio_get_sample( &plink_file, sample_id );
struct pio_locus_t *locus = pio_get_locus( &plink_file, locus_id );
printf( "Individual %s has genotype %d for snp %s.\n", sample->iid, snp_buffer[ sample_id ], locus->name );
}
locus_id++;
}
free( snp_buffer );
pio_close( &plink_file );
return EXIT_SUCCESS;
}
(The only difference is that their original example code is C, and now I use C++)
However, I got the undefined reference to
problems, as following:
undefined reference to 'pio_open'
undefined reference to 'pio_one_locus_per_row'
undefined reference to 'pio_row_size'
undefined reference to 'pio_next_row'
undefined reference to 'pio_num_samples'
undefined reference to 'pio_get_sample'
undefined reference to 'pio_get_locus'
undefined reference to 'pio_close'
From the header file, we can see that these are all defined.
I wonder how I can edit the CMakeLists.txt
file to avoid this problem?
Here is my current CMakeLists.txt
file.
cmake_minimum_required(VERSION 3.3)
project(PlinkTest)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
set(SOURCE_FILES main.cpp)
add_executable(PlinkTest ${SOURCE_FILES})
Thanks!