33

I am trying to build program with multiple files for the first time. I have never had any problem with compliling program with main.cpp only. With following commands, this is the result:

$ g++ -c src/CNumber.cpp src/CNumber.h -o src/CNumber.o
$ g++ -c src/CExprPart.cpp src/CExprPart.h -o src/CExprPart.o
$ g++ -c src/CExpr.cpp src/CExpr.h -o src/CExpr.o
$ g++ -c src/main.cpp -o src/main.o
$ g++ src/CNumber.o src/CExprPart.o src/CExpr.o src/main.o -o execprogram
src/CNumber.o: file not recognized: File format not recognized
collect2: error: ld returned 1 exit status

What could cause such error and what should I do with it? Using Linux Mint with gcc (Ubuntu/Linaro 4.7.2-2ubuntu1). Thank you

Community
  • 1
  • 1
RuinerCZ
  • 333
  • 1
  • 3
  • 5

3 Answers3

41

This is wrong:

 g++ -c src/CNumber.cpp src/CNumber.h -o src/CNumber.o

You shouldn't "compile" .h files. Doing so will create precompiled header files, which are not used to create an executable. The above should simply be

 g++ -c src/CNumber.cpp -o src/CNumber.o

Similar for compiling the other .cpp files

Michael Petch
  • 46,082
  • 8
  • 107
  • 198
nos
  • 223,662
  • 58
  • 417
  • 506
  • So, as far I understand it, builder is able to find these header files by itself due to #include directives, right? – RuinerCZ Jun 15 '13 at 18:43
  • @user2489350 Yes. Depending on where they are located. You can specify additional paths to search for #include files with the -I argument to gcc/g++ – nos Jun 15 '13 at 18:44
35

I ran into this error in building something - it turned out to be due to a previous build failing while compiling a source file to an .o file - that .o file was incomplete or corrupted, so when I tried another build it gave this error on that file.

The solution was to just delete the .o file (or run make clean, if you have a makefile with that target).

Brian Burns
  • 20,575
  • 8
  • 83
  • 77
0

Try putting all of the following files in one directory:

example.cpp:

#include<iostream>
#include<string>

#include "my_functions.h"

using namespace std;

int main()
{
    cout << getGreeting() << "\n";

    return 0;
}

my_functions.cpp:

#include<string>
using namespace std;

string getGreeting()
{
    return "Hello world";
}

my_functions.h:

#ifndef _MY_FUNCTIONS_H
#define _MY_FUNCTIONS_H

#include<string>
using namespace std;

string getGreeting();

#endif

Then issue these commands:

$ g++ example.cpp my_functions.cpp -o myprogram
~/c++_programs$ ./myprogram
Hello world
7stud
  • 46,922
  • 14
  • 101
  • 127
  • Thanks for reply. It builds fine. If I use just ./myprogram instead of your second line, I get correct output (hello world) – RuinerCZ Jun 15 '13 at 18:33