0

Possible Duplicate:
What is an undefined reference/unresolved external symbol error and how do I fix it?

I have main.cpp:

#include "censorship_dec.h"

using namespace std;

int main () {
    censorship();
    return 0;
}

this is my censorship_dec.h:

#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;

void censorship();

this is my censorship_mng.cpp:

#include "censorship_dec.h"
using namespace std;

void censorship()
{
   cout << "bla bla bla" << endl;
}

I tried to run these files in SSH (Linux), so I wrote: make main, but I got:

g++     main.cpp   -o main
/tmp/ccULJJMO.o: In function `main':
main.cpp:(.text+0x71): undefined reference to `censorship()'
collect2: ld returned 1 exit status
make: *** [main] Error 1

please help!

Community
  • 1
  • 1
Maor Cohen
  • 936
  • 2
  • 18
  • 33

3 Answers3

5

You have to specify the file where censorship is defined.

g++ main.cpp censorship_mng.cpp -o main
yiding
  • 3,482
  • 18
  • 17
  • in my function of censorship, I have another callings to another functions. so I got: /tmp/ccBpBk4A.o: In function `censorship()': censorship_mng.cpp:(.text+0x112): undefined reference to `read_files(char*, char*)' censorship_mng.cpp:(.text+0x129): undefined reference to `make_string(int&, char*, char (*) [21])' censorship_mng.cpp:(.text+0x139): undefined reference to `read_files(char*, char*)' censorship_mng.cpp:(.text+0x150): undefined reference to `make_string(int&, char*, char (*) [21])' collect2: ld returned 1 exit status – Maor Cohen Jan 15 '13 at 11:41
  • 1
    You need to add the files those symbols are defined in too. – yiding Jan 15 '13 at 11:42
3

You must add censorship_mng.cpp in your compilation command:

g++ main.cpp censorship_mng.cpp -o main


Another solution (if you really don't want change your compile command) is making void censorship(); to a inline function and move it from .cpp to .h.

censorship_dec.h:

#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;

inline void censorship()
{
  // your code
}

And remove void censorship() from censorship_mng.cpp file.

masoud
  • 55,379
  • 16
  • 141
  • 208
0

once your project starts using several source-files to be compiled into a single binary, manual compilations become tedious.

this is usually the time when you start using a build-system, such as a Makefile

a very simple Makefile that uses default build-rules could look like

default: main

# these flags are here only for illustration purposes
CPPFLAGS=-I/usr/include
CFLAGS=-g -O3
CXXFLAGS=-g -O3
LDFLAGS=-lm

# objects (.o files) will be compiled automatically from matching .c and .cpp files
OBJECTS=bar.o bla.o foo.o main.o

# application "main" build-depends on all the objects (and linksthem together)
main: $(OBJECTS)
umläute
  • 28,885
  • 9
  • 68
  • 122