30

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

4

3 回答 3

38

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

于 2013-06-15T18:22:37.460 回答
29

我在构建某些东西时遇到了这个错误 - 结果是由于之前的构建在将源文件编译为 .o 文件时失败 - .o 文件不完整或损坏,所以当我尝试另一个构建时它给出了这个错误在那个文件上。

解决方案是只删除 .o 文件(或运行make clean,如果您有带有该目标的 makefile )。

于 2016-01-11T23:48:47.653 回答
0

尝试将以下所有文件放在一个目录中:

例子.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

然后发出这些命令:

$ g++ example.cpp my_functions.cpp -o myprogram
~/c++_programs$ ./myprogram
Hello world
于 2013-06-15T18:16:18.177 回答