-1

I wrote a code split into several .h, .cpp files two functions take string type arguments (the code fragment below) I am getting this error:

/usr/bin/ld: /tmp/cclLgueo.o: in function `main':
main.cpp:(.text+0x1dc): undefined reference to `doloop(std::__cxx11::basic_string<char, 
std::char_traits<char>, std::allocator<char> >)'
/usr/bin/ld: main.cpp:(.text+0x238): undefined reference to 
`detect(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
collect2: error: ld returned 1 exit status

What does it mean? Code:

//File: main.cpp (fragment)
string loop;
doloop(loop);

Header:

#ifndef func_h
#define func_h
#include <string>
using namespace std;
void detect(string cmd);
... void
void doloop(string con);
... void
#endif

func.cpp:

void doloop(string con)
{
short y; // Fragment
}
//detect function is similar

##Compiler command: "g++ main.cpp"

Maniues
  • 125
  • 1
  • 5

1 Answers1

0

You need to compile all the translation units:

g++ func.cpp main.cpp
Jarvis
  • 8,494
  • 3
  • 27
  • 58
  • /usr/bin/ld: /tmp/ccBT2Up3.o:(.bss+0x0): multiple definition of `board'; /tmp/ccd85wOB.o:(.bss+0x0): first defined here /usr/bin/ld: /tmp/ccBT2Up3.o:(.bss+0x1d4c0): multiple definition of `pointer'; /tmp/ccd85wOB.o:(.bss+0x1d4c0): first defined here collect2: error: ld returned 1 exit status – Maniues Dec 26 '20 at 18:47
  • @Maniues Add guards (e.g. `#pragma once`) to your header files as well. – πάντα ῥεῖ Dec 26 '20 at 18:48
  • I added and the error still occurs – Maniues Dec 26 '20 at 18:59
  • I replicated the source and headers from your question and it compiles normally (given you are including the header file in correct source files). – Jarvis Dec 26 '20 at 19:06
  • I have got 2 headers: vars.h func.h in vars.h I have got int *pointer and int board[1000] in main.cpp / func.cpp: #include "vars.h" #include "func.h> – Maniues Dec 26 '20 at 19:09
  • You are getting an error because of a header which I can’t see and hence can’t fix. Also, the issue is no longer related to compilation but definition of your header files, so post them all. Ask your issue in a separate question and mark this answer as accepted to close the issue. – Jarvis Dec 26 '20 at 19:11
  • Unfortunately I can't post next question... – Maniues Dec 26 '20 at 19:17
  • You mentioned the content in `vars.h`, what does `func.h` contain? – Jarvis Dec 26 '20 at 19:17
  • vars.h - variables. func.h - functions (for example: int function(); ) – Maniues Dec 26 '20 at 19:25