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
asked Jun 15, 2013 at 17:58
2
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
45.3k8 gold badges104 silver badges190 bronze badges
answered Jun 15, 2013 at 18:22
nosnos
220k56 gold badges409 silver badges499 bronze badges
2
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).
answered Jan 11, 2016 at 23:48
Brian BurnsBrian Burns
19.5k8 gold badges82 silver badges74 bronze badges
1
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
answered Jun 15, 2013 at 18:16
7stud7stud
45.8k14 gold badges95 silver badges124 bronze badges
1
- Печать
Страницы: [1] Вниз
Тема: Проблема компиляции Си программы при помощи gcc (Прочитано 3265 раз)
0 Пользователей и 1 Гость просматривают эту тему.

solyr
Пытаюсь откомпилировать программу в Ubuntu Desktop 8.04 Hardy Heron Установил пакеты gcc и build-essential. Пробую откомпилировать программу gcc имя_программы Выдает следующее сообщение
sajan@sajan-desktop:~/soft$ gcc prg4
prg4: file not recognized: File format not recognized
collect2: ld returned 1 exit status
Может проблема в кодировке исходного кода. Локализация по умолчанию в UTF-8. Пробовал сохранять исходный код программы в кодировке UTF-8, KOI, виндовозной ничего не помогает. То же самое. Посоветуйте в чем может прблема?
И ище вопрос. Стандартные Си шные хеадеры автоматически подключаются компилятором?
« Последнее редактирование: 02 Декабря 2009, 17:16:25 от solyr »
GOTO_sHELL
Переименуй файл в prg4.c
Пользователь решил продолжить мысль 02 Декабря 2009, 17:21:26:
хеадеры подключаются директивами include в файле с кодом.
« Последнее редактирование: 02 Декабря 2009, 17:21:26 от GOTO_sHELL »

solyr
не думал что gcc к расширениям в Linuxe требователен. Спасибо, программа откомпилировалась

wl
не думал что gcc к расширениям в Linuxe требователен
Гы-гы…
Для справки: операционная система линукс, точнее ее файловая система не знает, что такое «расширение имени файла». Это понятие появилось лет 20 назад в DOS, поскольку 8 символов оказалось недостаточно, с DOS же и умерло.
Здесь и точка, и все, что после нее, является такой же полноценной частью имени файла, как и все остальное.
Винда позволяет ленивым юзерам части имен скрывать.
« Последнее редактирование: 03 Декабря 2009, 11:32:33 от wl »
На свете феньки есть такие, брат Горацио, которых лохи просто не секут. (Шекспир, «Гамлет», вольный перевод)

Riateche
Можно задать язык вручную: gcc -x c prg4
Подробнее смотрите в мане

solyr
понял насчет расширения. Я даж не подозревал что после точки указывается язык компиляции. Сенкс.

wl
понял насчет расширения. Я даж не подозревал что после точки указывается язык компиляции. Сенкс.
Чего???
Вы ничего не поняли!
Никаких языков после точки не указывается!
Компилятор должен получить в параметрах имя файла.
Вы ему указали prg4.
Поэтому он честно попытался открыть файл с именем prg4 в текущей директории.
Однако, Вы компилятор обманули — файл с текстом программы назывался prg4.c, а в файле prg4 было что-то еще.
На свете феньки есть такие, брат Горацио, которых лохи просто не секут. (Шекспир, «Гамлет», вольный перевод)

solyr
исходный код программы был изначально в prg4 Он никак не компилился Выдавал сообщение в что указано в первом посте После того как приписал к имени файл .с нормально скомпилил программу и выдал a.out

Riateche
Чего???
Вы ничего не поняли!
Никаких языков после точки не указывается!Компилятор должен получить в параметрах имя файла.
Вы ему указали prg4.
Поэтому он честно попытался открыть файл с именем prg4 в текущей директории.
Однако, Вы компилятор обманули — файл с текстом программы назывался prg4.c, а в файле prg4 было что-то еще.
По-моему, это вы ничего не поняли. Имя файла было указано правильно. gcc отказался его компилировать потому, что gcc действительно определяет язык программы по расширению.
- Печать
Страницы: [1] Вверх
Topic: Linker error (file not recognized: File format not recognized) (Read 53677 times)
ddam1
Hello, I’m doing a simple application to test the C++ capabilities and to learn some 
Using CodeBlocks to compile with MinGw I obtain the error «file not recognized: File format not recognized» when linking an header file for example:
#include <string>
//#include "aryan.h"#ifndef DBWORKER_H_INCLUDED
#define DBWORKER_H_INCLUDED
using namespace std;
class DBWorker {
public:
DBWorker(string dbname);
bool checkManufacturer(string manufacturer);
bool checkCategory(string cat);
// Aryan checkArticle(Aryan article, bool forceUpdate);
private:
bool createManufacturer(string manufacturer);
bool createCategory(string cat);
string dbname;
};
#endif // DBWORKER_H_INCLUDED
I’ve comment out all the «real code» of the class but the error persists 
The complete log is this:
-------------- Build: Release in gTintargossPrices ---------------
Precompiling header: DBWorker.h
Precompiling header: csvparser.h
Compiling: aryanparser.cc
Compiling: csvparser.cpp
Precompiling header: aryan.h
Compiling: main.c
Compiling: DBWorker.cpp
Linking console executable: binReleasegTintargossPrices.exe
DBWorker.h.gch: file not recognized: File format not recognized
collect2: ld returned 1 exit status
Process terminated with status 1 (0 minutes, 7 seconds)
0 errors, 0 warnings
DBWorker.h.gch is a file created by CodeBlocks from DBWorker.h.
Hope you can help me and thanks to all in advance
Pd: I don’t know if the problem is from codeblocks or from MinGW or inclusive from my own code
Logged
Right-click your header file, select properties, choose the Build tab, and uncheck the «Compile file» and «Link file» options. Do this for each header file. You should only ever use the Compile option on a header if you specifically want it to be used as a precompiled header, and you should never use the Link option for a header.
Logged
ddam1
I’ve found the line with the problem, is this:
mingw32-g++.exe -LC:GTKlib -LD:TempCodeBlockslib -o binReleasegTintargossPrices.exe aryan.h.gch DBWorker.h.gch csvparser.h.gch objReleasecsvparser.o objReleasearyanparser.o objReleasemain.o objReleaseDBWorker.o -lgtk-win32-2.0 -lgobject-2.0 -lglib-2.0 ……Descargasdtl.3.6.10only_liblinkerlibdtl_proj.a
if remove this «aryan.h.gch DBWorker.h.gch csvparser.h.gch» the command works ok, are there any way to do this from the IDE?
Logged
ddam1
Logged
- Forum
- Windows Programming
- file not recognized: File format not rec
file not recognized: File format not recognized
Hi
I am using eclipse.I got error.I am using g++ complier.
*.o : file not recognized: File format not recognized
collect2: ld returned 1 exit status
Please any one help me..
what exactly you are doing, can you explain a bit?
Hi
thanks for ur reply.
I got link error.Ecplise editor created the object file for that .cpp file.After compiling, object files and library files are linking.
at that time i got this error.
For Example, SGConfiguration.cpp —————> SGConfiguration.o
hello.cpp ——————————> hello.o
this is the full error
./SGConfiguration.o: file not recognized: File format not recognized
collect2: ld returned 1 exit status
This same program i complied successfully in Netbeans.
What can i do for this error?
Last edited on
you have only one file??
try compiling directly.
if you have only one file then you can do simple g++ «file_name».
like g++ SGConfiguration.cpp. thats all.
if you have multiple files then you can create makefile for them. i can help you in creating your makefile.
Hi
no….
I have multiple file.Totally 350 files (approximately).
how can i create make file.
help me….

actually i dont have any idea of netbeans or eclipse… how they work or compile the source..
i just saw you are working on windows.. otherwise you could have used autoconf and automake to create makefiles on linux/unix for large number of files.. thats a very easy process.. but i dont know if automake work on windows..leave this..
which platform you compile your code with netbeans??
on windows it is easy to use visual studio but i dont know if you have visual studio?
Hi
I used Linux platform for compile the code with Netbeans.
Could u explain autoconf and automake to create makefile on Linux/UNIX.
ok.. lets make a simplest project.
mkdir test_proj
cd test_proj
mkdir src bin
touch configure.ac Makefile.am
AC_INIT(src/main.cpp)
AM_INIT_AUTOMAKE(add, 1.0)
AC_PROG_CXX
AC_HEADER_STDC
AC_SUBST(CFLAGS)
AC_SUBST(LDFLAGS)
AC_OUTPUT(Makefile src/Makefile)
#Makefile.am
SUBDIRS = src
cd src
touch main.cpp add.cpp add.h Makefile.am
#the output program
bin_PROGRAMS = ADD
AM_CXXFLAGS = $(INTI_CFLAGS)
CFLAGS = -Wall -O2
#ADD_SOURCES, you have to attache ADD_ with the options
ADD_SOURCES = main.cpp add.cpp
#add ld here like lstdc++ etc etc
ADD_LDADD = @LDFLAGS@
#add ld path here,like -L /usr/local/lib
ADD_LDFLAGS =
#add include paths for any other header files with -I switch
INCLUDES =
|
|
|
|
|
|
thats it.. you are dont..
cd ..
aclocal
autoconf —add-missing
automake
./configure //this will create your makefile
make //this will create a binary with name «add»
thats all you need to do.. now if you add any new file to project, just add it to Makefile.am and aclocal to make again.
if autoconf or automake give error for any missing files, create these file using touch. it may give error for INSTALL, COPYING, README, NEWS, depcomp, AUTHORS etc etc.. so create these files manually.
Topic archived. No new replies allowed.

If you want to become an expert at fixing this undefined reference in your program, keep reading this complete guide that contains all the details.
Why Is the collect2: Error: Ld Returned 1 Exit Status Happening?
This specific collect2: error: ld returned 1 exit status error message appears due to previous errors in your document, especially when working with C++. It represents one of the most common errors web developers face but it is also one of the easiest ones to fix. In other words, this error is there to indicate that the linking step in the process of creating faced certain problems.
This is going to create an undefined reference because the exit status is more than the value of zero. You can run multiple steps to create a search thread that is going to eliminate the problem. We are going to list and explain the various methods you can use to fix this error in your document. Continue reading the following section of this article to learn more about the debugging process.
How To Fix This Error Inside Your Program
The easiest and most common method of fixing this error requires you to completely delete the existing executable file that is running in the background of your program. However, as is the case with most other bugs, this solution might not work for everyone and every single time. Lucky for you, programming languages allow users to fix an error in multiple ways, in case any of the previous ones does not work.
This is called a process of debugging, where you are trying to completely remove an error you have encountered in your program. No matter how serious the error may be, the debugging process always starts with an inspection of the problem. After that, locate where the error is coming from and apply all the necessary changes to the code.
Let us now learn something more about the ways of debugging this error.
– Listing All the Possible Methods for Debugging This Error
In this part of the guide, we are going to list the possible methods for debugging and also briefly explain their function. Let us take a deep dive at the following list that shows the most common ways of fixing this error:
- Deleting the existing executable file inside your program: The file may have failed because it is locked in a different location, such as an antivirus.
- It is possible to try and rename that specific executable file in your program. Then, you are supposed to restructure the contents, and you are done. Renaming the file helps the program to create an additional executable file.
- In case none of this works, you should try restarting your computer and redo the first step. This solution shows that debugging does not always have to be complicated.
In theory, this is all it takes to completely remove this error from your syntax. However, it is always best to learn from examples. That is why in the following section of this article, we are going to show you example codes to easily fix this error.
– A Common Error in the Gem Native Extension
Many web developers face certain problems once working with extensions for their browsers. One such bug appears when you are trying to install a gem inside the native extension on your browser.
The reason why we are explaining the native extension is that the collect2 error usually appears during the process of installing a gem. To better understand what this means, you should take a look at the complete syntax.
Take a closer look at the following code that is going to initiate the collect2 error:
Building a proper native extension. This might take a while…
ERROR: Error installing json:
ERROR: Failed to generate gem native extension.
/home/foobar/.rvm/ruby-2.4.7/bin/ruby -r ./siteconf134617815-3312439-1i9lahdrj.rb extconf.rb
creating Makefile
make “DESTDIR=” clean
make “DESTDIR=”
compiling generator.c
linking shared-object json/ext/generator.so
/usr/bin/ld: cannot find -lgmp
collect2: error: ld returned 1 exit status
make: *** [generator.so] Error 1
make failed, exit code 2
Gem files will remain installed in /home/foobar/.rvm/gems/ruby-2.4.7/gems/json-1.8.3 for inspection.
Results logged to /home/foobar/.rvm/gems/ruby-2.4.7/extensions/x86_64-linux/2.2.0/json-1.8.3/gem_make.out
As you can see, this is the complete code for the collect2 error inside your program. There is certainly something you can do to the syntax to debug this error and make the program functional again. Indeed, we are going to change some things in the library and this is going to completely remove the error. Take a look at the following section of this article to learn more.
– Using the Debugging Library Syntax for the collect2 Error
As previously explained, you are supposed to change certain things inside the library to fix this error. For this, you are going to need the gmp function to locate the correct files and return the incorrect status. Open the code with the cache search gmp function and include all the additional tools inside.
The following syntax shows how to properly use the gmp function to fix this error:
$ apt-cache search gmp
libgmp-dev – Multiprecision arithmetic library developers tools
libgmp10 – Multiprecision arithmetic library
libgmp10-doc – Multiprecision arithmetic library example code
libgmp3-dev – Multiprecision arithmetic library developers tools
libgmpxx4ldbl – Multiprecision arithmetic library (C++ bindings)
[…]
Be aware that the syntax may be subject to changes. As this example shows, the annoying collect2 error does not have to be complicated to locate and fix. However, pay attention to the exact location of the gmp function because this may sometimes be the difference between a correctly and incorrectly executed code. Let us now learn other things about this common error in your program.
– Facing This Error in Dev C++
As previously explained, the collect2 error may usually appear once working with Dev C++. It refers to a specific reference to a name where the linker cannot define the way it looks based on the object files. This also applies to all the libraries that make up your document.
Lucky for you, fixing the error is done in the same manner as previously taught. All you have to do is to follow the steps discussed in this article and the problem is going to disappear. To learn more about this error, continue reading the FAQ section of this article.
FAQs
Here are the answers to some of your questions regarding this error.
– What Is collect2 Exe?
Collect2 represents a utility that web developers use to arrange certain initialization functions during the start time. In other words, it is used to link the program and the adequate functions, while creating a table inside a temporary file. Then, it is going to create a second link with the program but include a different file.
– What Does Error 1d Returned 1 Exit Status Mean?
The returned 1 status refers to an error in your document that is created due to previous errors. It is used as an indicator to point out that certain linking steps during the building process have bugs. To fix the error, you are supposed to refer to all the previous functions and locate the part of the program that is operating incorrectly.
– How To Combine Two Files in C++?
You can start combining two files in C++ by creating two separate source files on your server. The process of combining two C++ files is important because you can combine two different programs and functions. Since the collect2 error usually appears during this process, it is important to understand how the files are merged together.
There are several steps you are supposed to closely follow, as shown in the following list:
- Create two separate C++ source files on your server.
- Both files should be saved inside the same location on the server.
- Open the Command Prompt tool and run the various commands from your files.
- The tool is going to merge the two separate source files together and comply their functions.
- Install the C++ Complier Program to run the newly-created file without any bugs.
This is all it takes to create a complex C++ file without facing any collect2 errors in your server. You can use this method for any two C++ files.
This section wraps everything important you were supposed to know about the collect2 error in your document. Let us now summarize the details.
Final Conclusion and Further Notes
This specific exit status error message is easily fixed by removing an existing executable file inside your document. Let us take a deep dive at the following list that contains all the important details from this article:
- The collect2 error is easily fixed by shutting down a program that is running in the background
- Web developers usually face this problem once working with Dev C++ and other files
- The Gem native extension usually displays this error alongside the complete syntax but it can be easily fixed
- It is important to know the meaning of collect2 to debug the error more efficiently
- It is possible to merge two C++ source files in five basic steps without caring about this error

- Author
- Recent Posts
Position Is Everything: Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL.
Forum Updated on Feb 6th
This topic has been deleted. Only users with topic management privileges can see it.
-
I am currently using qt version 5.4 (ubuntu os)
The following error occurs during the build.
Upload related settings.
I would be grateful if you could find out what I’m missing.< Error >
File not recognized: File format not recognized
/lib/x86_64-linux-gnu/libgcc_s.so.1
Collect2: error: ld returned 1 exit status< compilers >
/root/crosscompile-tools/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian-x64/bin/arm-linux-gnueabihf-g++<debuggers>
/root/crosscompile-tools/tools/arm-bcm2708/arm-rpi-4.9.3-linux-gnueabihf/bin/arm-linux-gnueabihf-gdb -
@this It’s trying to load a 64-bit libgcc for your arm build which is 32-bit and a different architecture.
-
@ambershark
Do you want to run the compiler and debugger in 64bit?
I did that.
I’ve also run 32bit, and I’ve run 64bit.
But the same error occurs.I do not understand well.
Could you explain more? -
@this You are cross compiling, right? In this case you need a cross compiled Qt (built with the same cross compiler).
lib/x86_64-linux-gnu/libgcc_s.so.1 — this is for x86_64 architecture
/root/crosscompile-tools/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian-x64/bin/arm-linux-gnueabihf-g++ — this is for ARM
ARM != x86_64 -
@jsulm Yes, cross-compile right.
So the compiler
/ root / crosscompile-tools / tools / arm-bcm2708 / gcc-linaro-arm-linux-gnueabihf-raspbian-x64 / bin / arm-linux-gnueabihf-g ++
.
What do you need to do more? -
@this As I said: you need to cross compile Qt. The Qt you have on your Ubuntu machine is for x86_64 not ARM.
-
@jsulm said in File not recognized: File format not recognized error:
cross compile Qt
sorry but,
I do not understand well.
I have installed everything related to cross compile
What do I need to do to set up arm cross compilation in qt? -
@this If you want to write Qt applications for your target device then you need Qt built for that device.
«I have installed everything related to cross compile» — what about Qt? Does your cross compilation set-up contain Qt for your target device? You cannot use your Ubuntu Qt packages for your target device as those are compiled for x86_64 not ARM.
What exactly did you install?
There is a description how to cross compile Qt for RaspberryPi: http://wiki.qt.io/Raspberry_Pi_Beginners_Guide -
@jsulm I have completed installation related to crosscompile.
I created a new project and proceeded with the build.
I also confirmed that an executable file is created in raspberry pi. I also confirmed that debugging is going well.So the crosscompile completed successfully.
By the way,
I have a problem when I crosscompile qt that I have already worked on (ubuntu qt)
Can not I crosscompile the qt I’ve been working on? -
@this Sorry, now I’m completely lost! Can you please clearly explain what you are really doing? You were talking about Qt from Ubuntu which you installed, now you say you’re building on RaspberryPi. Are you building on RaspberryPi for RaspberryPi (which isn’t cross compilation), or do you want to build on RaspberryPi for your Ubuntu PC?
If you’re crsoss compiling from RaspberryPi to Ubuntu then why do you use ARM cross compiler?«I have completed installation related to crosscompile» — what did you install and where?
«I have a problem when I crosscompile qt that I have already worked on (ubuntu qt)
Can not I crosscompile the qt I’ve been working on?» — I don’t know what you mean. -
@jsulm I do not speak English well.
So I use a translator.
So it seems that there is a problem in communication.I’m proceeding with ‘ubuntu-> raspberrypi’.
The following homepage is an item installed to crosscompile.
Https://medium.com/@amirmann/how-to-cross-compile-qt-for-raspberry-pi-3-on-linux-ubuntu-for-beginners-75acf2a078cA new project was created and cross-compiled successfully.
Executable file created in rasspberry pi.
Debugging went well.By the way,
I tried to crosscompile a project that was working with qt on ubuntu pc in the past.So I want to crosscompile with raspberry pi the project I worked on in the past.
However, the above error occurs.I want to build the qt that I worked on in the past with cross-compiled qt.
I’m sorry I’m not good at English.
I do not know if it was delivered properly. Sorry. -
@this said in File not recognized: File format not recognized error:
Executable file created in rasspberry pi.
You probably mean FOR RaspberryPi not IN.
In the first post you wrote:
«< Error >
File not recognized: File format not recognized
/lib/x86_64-linux-gnu/libgcc_s.so.1
Collect2: error: ld returned 1 exit status»
This looks to me like you’re trying to use your Ubuntu x86_64 Qt to cross compile for RaspberryPi. This cannot work. You need to use your cross compiled Qt. -
@jsulm Thank you.
I solved the problem.
I typed LIBS + = -L / lib / x86_64-linux-gnu / -lz in my .pro file
I modified it for arm, and it builds well.
Thank you for your help. -
@this excuse me, I have the same problem, I’m trying to complie in my raspberry pi, and the same error appears, I’m using a dynamic library (.so) and it seems that the problem its with the linker step, I see that you resolved the problem with that comand line, but Can you explain me more how to use that line? Thanks a lot !!
-
@oswaldopr said in File not recognized: File format not recognized error:
I’m trying to complie in my raspberry pi, and the same error appears, I’m using a dynamic library (.so)
You need to be sure the .so file you’re using is for the right platform (i.e. ARM)


