0

I am trying to compile a simple code using cmake and I getting an error. The code and cmake file are as below. The test.cpp is the main file in which i have directly included test1.cpp. I have also included my CMake file and the error that I am getting on performing make.

test.cpp

#ifndef _IOSTREAM_
#include<iostream>
#endif
#include"test1.cpp"
using namespace std;
int main()
{
printing("hello");
return 0;
}

test1.cpp

#ifndef _IOSTREAM_
#include<iostream>
#endif
#include<string>
using namespace std;
void printing(string s)
{
cout<<s<<endl;
return;
}

CMakeLists.txt

cmake_minimum_required(VERSION 2.6)
set(CMAKE_C_COMPILER "/usr/bin/clang")
set(CMAKE_CXX_COMPILER "/usr/bin/clang++")
project(test)
set(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} -std=c++11)
add_executable(test test.cpp test1.cpp)

Error

CMakeFiles/test.dir/test1.cpp.o: In function 
printing(std::__cxx11::basic_string<char, std::char_traits<char>, 
std::allocator<char> >):
/home/vatsal/Desktop/test/test1.cpp:(.text+0x0): multiple definition 
of printing(std::__cxx11::basic_string<char, std::char_traits<char>, 
std::allocator<char> >)
CMakeFiles/test.dir/test.cpp.o:/home/vatsal/Desktop/test/test.cpp: 
(.text+0x0): first defined here
clang: error: linker command failed with exit code 1 (use -v to see 
invocation)
CMakeFiles/test.dir/build.make:98: recipe for target test failed
make[2]: *** [test] Error 1
CMakeFiles/Makefile2:67: recipe for target CMakeFiles/test.dir/all 
failed
make[1]: *** [CMakeFiles/test.dir/all] Error 2
Makefile:83: recipe for target all failed
make: *** [all] Error 2

1 Answers1

0

It happens because include cpp file is a bad idea.

After preprocessor work you'll get two defenition of void printing(string s) The first one is in test.cpp because you've incleded test1.cpp and the second one is in test1.cpp.

Solution is to create test1.h which contain declaration of function:

#include<iostream>
#include<string>
using namespace std;
void printing(string s);

Then fix test1.cpp:

#include "test1.h"
using namespace std;
void printing(string s)
{
    cout<<s<<endl;
    return;
}

And finaly replace #include"test1.cpp" with #include"test1.h" in test.cpp

Konstantin T.
  • 994
  • 8
  • 22