Error ld returned 1 exit status как исправить codeblocks

I'm using Code::Blocks v 16.1.0.0 along with the MINGW that came with it. There is a problem with the linker. I cannot link a single header / source file to a source file using #include "sth". To n...

There is a problem with the linker. I cannot link a single header / source file to a source file using #include «sth»

There isn’t a problem with the linker. You cannot link header files or sources files. You can only compile source
files (which may #include header files), to produce object files.

A header file that you #include can be a precompiled header file,
for compilers that support this concept, subject to compiler-specific restrictions
on its use (and despite the name, a precompiled header file is not compiled: it is not
an object file).

The linker can only link object files and dynamic libraries to produce an executable.
It can consume object files either directly or extract them from a static library.

Your failing linkage command:

g++.exe -LC:UsersusernameDocumentsCodeBlocksCMISC -o binDebugMISC.exe objDebugreadFileByChars.o readFileByChars.h.gch

shows that you are attempting to link a precompiled header readFileByChars.h.gch. The linker says:

readFileByChars.h.gch: file not recognized: File format not recognized

because a precompiled header is not an object file or a static or dynamic
library. It is not something the linker understands.

Correct your project options so that you are no longer passing readFileByChars.h.gch
as a linker input.

Presumably you have gone through the special steps
to generate the precompiled header readFileByChars.h.gch in your Code::Blocks project.
If you have followed that documentation correctly, there is nothing else you need to do that the documentation
does not mention. Your other project options do not need to tell the compiler or linker anything
about the precompiled header.

It is not necessary to use precompiled headers at all and, as you see, their
correct use is not foolproof, and is compiler-specific. I would
suggest you build this and other projects in the ordinary way, without precompiled headers,
until and unless you are facing obstructively long compilation times, which
a precompiled header might usefully curtail.

hi to all , I’ve  centos 7.5 in VM. I m trying to compile a shared library file. But hanging up with message:-

-------------- Build: Release in singlyll (compiler: GNU GCC Compiler)---------------

gcc -Wall -O2  -c "/opt/projects/code blocks/data structures/linkedlist/soproject/singlyll/singlyll/singlyll.c" -o obj/Release/singlyll.o
g++ -shared  obj/Release/singlyll.o  -o bin/Release/liblibsinglyll.so -s 
/usr/bin/ld: obj/Release/singlyll.o: relocation R_X86_64_32 against `.rodata.str1.1' can not be used when making a shared object; recompile with -fPIC
/usr/bin/ld: final link failed: Nonrepresentable section on output
collect2: error: ld returned 1 exit status
Process terminated with status 1 (0 minute(s), 1 second(s))
1 error(s), 0 warning(s) (0 minute(s), 1 second(s))

||=== Build: Release in singlyll (compiler: GNU GCC Compiler) ===|
error: ld returned 1 exit status

singlyll.h :-
—————

#ifndef SINGLYLL_H_INCLUDED
#define SINGLYLL_H_INCLUDED

#include <stdio.h>
#include <stdlib.h>

typedef struct node
{
    int data;
    struct node * link;
}node;

node *start, *p;

void display( struct node * start);
void search( struct node *start, int data);
 struct node * addatbegin( struct node *start, int data);
 struct node * addatend( struct node*start, int data);
 struct node * addafter( struct node * start, int data, int item);
 struct node * addberfore( struct node * start, int data, int item);

 struct node * createlist( struct node * start, int n);

 struct node * del( struct node* start, int data);
 struct node * reverse( struct node *start);

#endif // SINGLYLL_H_INCLUDED

singlyll.c :-
—————

#include "singlyll.h"

//struct
//{
//    int data;
//    struct node * link;
//}node;

void display(struct node* start)
{
    struct node *p;
    if(start == NULL)
    {
        printf("list is emptyn");

        return;
    }

    printf("List : ");

    for(p = start; p != NULL; p = p->link)
    {
        printf("%d t", p->data);
    }
    printf("nn");
}

void search(struct node* start, int item)
{
    struct node* p = start;

    int pos = 1;

    for(;p != NULL; p = p->link)
    {
        if(p->data == item )
        {
            printf( "item %d found at position %d n", item, pos);
        }
        pos++;
    }

    printf("item %d not found in listn", item);
}

struct node* addatbegin( struct node* start, int item)
{
    struct node*temp  = (struct node*) malloc(sizeof(node));

    temp->data = item;

    temp->link = start;

    start = temp;

    return start;

}

struct node* addatend(struct node* start, int item)
{
    struct node* p = start;
    struct node* temp = start;

    temp = (struct node*) malloc(sizeof(node));
    temp->link = NULL;

    while(p->link!= NULL)
         p = p->link;
    p->link  = temp;

    return start;
}

struct node* addafter(struct node* start, int item, int data)
{
    struct node*p = start, *temp;

    while( p != NULL)
    {
        if(p->data == item)
        {
            temp = (node*) malloc(sizeof(node));
            temp->data = item;
            temp->link = p->link;
            p->link = temp;

            return start;
        }

        p = p->link;
    }

    printf(" not present in the listn");
    return start;
}

struct node* addberfore(struct node* start, int data, int item)
{
    struct node*temp, *p;

    if(start == NULL)
    {
        printf("list is emptyn");
        return start;
    }

    /*insert before the first struct node*/

    if(item == start->data)
    {
        temp = (node*) malloc(sizeof(node));
        temp->data = data;
        temp->link = start;
        start = temp;

    }

     p = start;

     while(p->link != NULL)
     {
         if(p->link->data == item)
         {
            temp = (node*)malloc(sizeof(node));
            temp->data = data;

            temp->link = p->link;

            p->link = temp->link;

            return start;
         }

         p = p->link;
     }

     printf("%d not present in the listn", item);
     return start;
}

 struct node* createlist(struct node* start, int n)
 {
    int i, data;

    start = NULL;

    if( n == 0)
    {
        return start;
    }

    printf("Enter elements to be inserted : ");

    scanf("%d", &data);

    start = addatbegin(start, data);

    for( i = 2; i <= n; i++ )
    {
        printf("Element to be inserted : ");
        scanf("%d",&data);

        start = addatend(start, data);
    }

    return start;
 }
struct node* del(struct node* start, int data)
{
    struct node*p, *temp;

    if(start == NULL)
    {
        printf("The list is empty n");
        return start;
    }

    if(start->data == data)
    {
        temp= start;
        start = start->link;
        free(temp);

        return start;
    }

    p = start;

    while(p->link != NULL)
    {
        if( p->link->data == data)
        {
            temp = p->link;
            p->link = temp->link;
            free(temp);

            return start;
        }
        p = p->link;
    }

    printf("Element %d not foundn", data);

    return start;
}

struct node* reverse(struct node* start)
{
    struct node*prev, *ptr, *next;

    prev = NULL;
    ptr = start;

    while(ptr->link != NULL)
    {
        next = ptr->link;
        ptr->link = prev;
        prev = ptr;
        ptr = next;
    }

    return start;
}

have any one solution for this. how to handle this «ld returned i exit status» problem.

Содержание

  1. Error ld returned 1 exit status codeblocks
  2. Arch Linux
  3. #1 2016-05-17 06:02:38
  4. CodeBlocks+MinGW86_64 Cross Compiler: ld returns 1 exit status.
  5. #2 2016-05-17 06:24:30
  6. Re: CodeBlocks+MinGW86_64 Cross Compiler: ld returns 1 exit status.
  7. #3 2016-05-17 12:12:34
  8. Re: CodeBlocks+MinGW86_64 Cross Compiler: ld returns 1 exit status.
  9. #4 2016-05-17 12:49:24
  10. Re: CodeBlocks+MinGW86_64 Cross Compiler: ld returns 1 exit status.
  11. #5 2016-05-17 12:58:23
  12. Re: CodeBlocks+MinGW86_64 Cross Compiler: ld returns 1 exit status.
  13. #6 2016-05-17 13:20:02
  14. Re: CodeBlocks+MinGW86_64 Cross Compiler: ld returns 1 exit status.
  15. #7 2016-05-17 13:34:32
  16. Re: CodeBlocks+MinGW86_64 Cross Compiler: ld returns 1 exit status.
  17. #8 2016-05-17 13:41:29
  18. Re: CodeBlocks+MinGW86_64 Cross Compiler: ld returns 1 exit status.
  19. #9 2016-05-17 13:59:10
  20. Re: CodeBlocks+MinGW86_64 Cross Compiler: ld returns 1 exit status.
  21. #10 2016-05-17 15:08:04
  22. Re: CodeBlocks+MinGW86_64 Cross Compiler: ld returns 1 exit status.
  23. Code :: Blocks error: ld вернул 1 состояние выхода
  24. 3 ответа
  25. 15 причин, почему CodeBlocks не работает
  26. 1. Не хватает нужных компонентов (компилятора, отладчика, библиотек)
  27. 2. Неверно указаны пути к компонентам
  28. 3. Символы кириллицы или пробелы в пути к программе CodeBlocks
  29. 4. Символы кириллицы или пробелы в пути к разрабатываемой программе
  30. 5. Не все пункты меню активны
  31. 6. При запуске компилятора ничего не происходит
  32. 7. Программа работает из CodeBlocks, но если запустить ее отдельно, то она сразу закрывается
  33. 8. CodeBlocks запускает предыдущую версию программы
  34. 9. Компиляция проходит без ошибок, но программа не запускается
  35. 10. Антивирус блокирует запись программы на диск
  36. 11. Windows блокирует работу CodeBlocks
  37. 12. Отладчик не останавливается на точке останова
  38. 13. Неверное указание пути к компилятору
  39. 14. Программа на GTK+ работает только в среде CodeBlocks
  40. 15. При запуске программы постоянно появляется окно консоли

Error ld returned 1 exit status codeblocks

I installed code blocks first time. I am using windows 10, code blocks version 20.03. When i am trying to compile code i am getting error:
ld.exe cannot find -lsprite
ld.exe cannot find -lbgi
error : ld returned 1 exit status.
I am running hello world code:

using namespace std;

int main()
<
cout Last edited on

The code is valid. I don’t recommend using code blocks. Try Visual Studio. You can run code online while learning until you figure it out:

I am using windows 10, code blocks version 20.03.

Condolences.

ld.exe cannot find -lsprite
ld.exe cannot find -lbgi
error : ld returned 1 exit status.

When you install Code::Blocks in Windows, it usually takes along some version of the MinGw compiler.
ld.exe is the MinGw linker.
Those error say the linker cannot find the libraries ‘bgi’ and ‘sprite’.

Browsing Internet, it seems bgi could be the “Borland Graphics Interface […] a graphics library bundled with several Borland compilers for the DOS operating systems since 1987” (Wikipedia), while sprite could be part of the SFML library.

It looks like you want to link against those libraries, but you haven’t provided your compiler the proper information (the directories) to find them.

using namespace std;

I just want to know that why am i getting those errors and how to resolve them?

You are getting those errors because you’re trying to link against the mentioned libraries the wrong way.
Either you haven’t installed them, or their aren’t in the directories you specified to the compiler, or you missed to specify the directories.

You can resolve those errors by providing the compiler the right information.

Nah, lsprite is not SFML.

OP, just make a new, empty project. Don’t use one of the existing project templates.

Go into your project/build settings and remove any linker options.

I tested my C:B 20.03 install, twice creating a new project. 1st using the Console application template wizard, 2nd time using the Empty project template.

Both compiled C++ «Hello World» code without a problem.

@gsmehta7, something about your installation is borked. I couldn’t even begin to try to guess what without a lot more information.

Good luck! I hope you get your problems solved.

And if/when you can compile code in C:B successfully let us know what you did. That could help others in the future who have the same/similar problems.

Источник

Arch Linux

You are not logged in.

#1 2016-05-17 06:02:38

CodeBlocks+MinGW86_64 Cross Compiler: ld returns 1 exit status.

Hello, I am creating a GUI for my science project, using FLTK.
The CodeBlocks default «GNU GCC Compiler» works fine.
Then I wanted to compile exe for my program for Windows use.
Add new compiler. check
Directories set to /usr/x86_64-w64-mingw32/include (compiler), /usr/x86_64-w64-mingw32/lib (linker) and /usr/x86_64-w64-mingw32/include (resource compiler)
Toolchains executables set to x86_64-w64-mingw32-gcc, x86_64-w64-mingw32-g++, x86_64-w64-mingw32-g++, x86_64-w64-mingw32-g++.
Rebuild. from no error to

They are mostly warning from FLTK.
But THIS:

stops me from rebuilding it, thus cannot have EXE file.
What is this? Searching gives me no answer.

#2 2016-05-17 06:24:30

Re: CodeBlocks+MinGW86_64 Cross Compiler: ld returns 1 exit status.

Some more info: the rebuild code from codeblocks:

the sucessful default rebuild (before cross compiling):

Other linker options:

remove these lines clears ld||unrecognized option ‘-z’| but still returns 1.

Last edited by kudykennedy (2016-05-17 06:55:02)

#3 2016-05-17 12:12:34

Re: CodeBlocks+MinGW86_64 Cross Compiler: ld returns 1 exit status.

Using GNU GCC COMPILER, compile success:

THEN USING CROSS COMPILER MINGW:

IT KEEPS SAYING THOSE .SO LIBRARIES I LINKED WAS IN WRONG FORMAT.
They compile just fine with GNU GCC COMPILER!
What is the difference .

Last edited by kudykennedy (2016-05-17 13:51:13)

#4 2016-05-17 12:49:24

Re: CodeBlocks+MinGW86_64 Cross Compiler: ld returns 1 exit status.

First, please calm down. All caps and excessive punctuation/exclamation points are not needed.

Second, you are linking to ELF shared objects for a win32 build. You need to use the win32 dlls provided by the mingw packages.

Also, is this any different from your other post or are you just cross posting the same problem?

«UNIX is simple and coherent. » — Dennis Ritchie, «GNU’s Not UNIX» — Richard Stallman

Online

#5 2016-05-17 12:58:23

Re: CodeBlocks+MinGW86_64 Cross Compiler: ld returns 1 exit status.

Ok, sorry. Changed to x86_64 mingw. Sill the same problem. My g++ is 64, all of my so are 64, still wrong format.
This only happens with those I need libraries. For a simple Hello World, no error, and .exe is created.
Even .so files in usr/lib64 won’t work. So you are saying, I have to link to dll files, instead of those .so files ?

#6 2016-05-17 13:20:02

Re: CodeBlocks+MinGW86_64 Cross Compiler: ld returns 1 exit status.

So you are saying, I have to link to dll files, instead of those .so files?

Yes. i686 vs x86_64 is not the issue. Windows does not use the same ELF format that linux does, so you cannot use linux *.so files, you need to link to windows libs which are .dll files.

The mingw compiler handles this for you for the standard libraries, that’s why your hello-world example worked fine. But as soon as you include other libs, you need to give the linker the path to the dlls. In most cases you can use mingw’s pkg-config to help with this, so just like in a linux build you could specify LDFLAGS from `pkg-config —libs

  • ` you can use mingw’s pkg-config the same way. I forget the exact path and name of mingw’s pkg-config but it follows similar naming conventions as the compilers.

    You would actually be fine with the i686 build though as any Windows system can still run Win32. Not long ago 32-bit builds seemed to be the norm and encouraged as they could run on any windows system while win64 could only run on 64 bit systems. This is still true, but 32 bit windows systems may be less common now.

    «UNIX is simple and coherent. » — Dennis Ritchie, «GNU’s Not UNIX» — Richard Stallman

    Online

    #7 2016-05-17 13:34:32

    Re: CodeBlocks+MinGW86_64 Cross Compiler: ld returns 1 exit status.

    Thanks, great. Some more questions though.
    1. I have to look for 32 bit / 64 .dll files for FLTK and LIBGL. Do you have a good source for these?
    2. What if I do not have Windows, can makefiles alone generate dll instead of .so? And how to achieve it?

    #8 2016-05-17 13:41:29

    Re: CodeBlocks+MinGW86_64 Cross Compiler: ld returns 1 exit status.

    1) The mingw group in the AUR, or the mingw repository. I don’t see fltk there though, so you might need to build that yourself. See any of the hundreds of other mingw PKGBUILDs for a template on how to build it. But in general, installing dependencies for mingw builds is just like installing dependencies for linux builds. If you’d build a package for linux using gcc and libABC, then to build for windows you’d need mingw-gcc and mingw-libABC. You cannot mix and match: your libraries must match the system targetted by the compiler.

    2) The dlls are the windows equivalent of .so files, you should not need to «generate» them, they are in the mingw packages for that lib — fltk again may be an exception, but you don’t need to do anything special to generate the dlls, just build and install a mingw fltk package. A makefile alone cannot generate anything, but a makefile with a mingw cross compiler does compile for windows, that’s it’s whole purpose.

    I can’t give a complete step-by-step as I’m no longer cross compiling on this system, but frankly I think you may need to take a step back and start a bit smaller. Use libs that are available already for mingw to get used to cross compiling. Then once you get used to it, making PKGBUILDs for other libs like fltk will be trivial. You could also just download the windows dlls from fltk’s upstream source and just drop them in your build directory — but this would seem a bit messy to me. EDIT: maybe not, fltk does not seem to distribute a windows build from what I can (quickly) find, just the source code.

    «UNIX is simple and coherent. » — Dennis Ritchie, «GNU’s Not UNIX» — Richard Stallman

    Online

    #9 2016-05-17 13:59:10

    Re: CodeBlocks+MinGW86_64 Cross Compiler: ld returns 1 exit status.

    Thank you wholeheartedly, not only saying where I’m wrong but also clearing my head on the whole cross-compiling issue.
    Marked solved. Long way to go until I can fully get rid of using Windows. Again, thanks.

    #10 2016-05-17 15:08:04

    Re: CodeBlocks+MinGW86_64 Cross Compiler: ld returns 1 exit status.

    Moderator: As far as I can tell, you had two threads going on the same topic. Even if the threads were different issues, the overreaching issue seemed to be cross compile link errors in a particular IDE I think this is of narrow interest, so I went ahead and merged the threads to keep things tidy.

    Nothing is too wonderful to be true, if it be consistent with the laws of nature — Michael Faraday
    Sometimes it is the people no one can imagine anything of who do the things no one can imagine. — Alan Turing

    How to Ask Questions the Smart Way

    Источник

    Code :: Blocks error: ld вернул 1 состояние выхода

    Я использую Code :: Blocks v 16.1.0.0 вместе с MINGW, который шел с ним. Есть проблема с компоновщиком. Я не могу связать один заголовок / исходный файл с исходным файлом, используя #include «sth» . Чтобы сузить проблему, у меня есть только 1 исходный и 1 заголовочный файл в моем проекте, но я не могу обойти эту ошибку независимо от того, какие файлы я использую, и какие опции я пробую.

    Это журнал сборки

    Это каталоги инструментов:

    У меня не было ни одного предыдущего запуска программ. У меня также работает автономный MINGW (без включения его папки bin в переменные среды, чтобы не перепутать кодовые блоки во время сборки), но для кодовых блоков я включаю предварительно упакованный, поставляемый с его установкой. Когда я нажимаю на опцию, чтобы связать файл заголовка в моем проекте, проект не будет построен (но если я не связываю файл, как я могу создать свое приложение?). Я повторяю, этот проект пуст, у меня есть только один заголовок и только один исходный файл. Я видел другие подобные вопросы об этом здесь, но их решения не работали. Помощь будет оценена. Спасибо.

    3 ответа

    Есть проблема с компоновщиком. Я не могу связать один заголовок / исходный файл с исходным файлом, используя #include «sth»

    С компоновщиком проблем нет. Вы не можете связать заголовочные файлы или исходные файлы. Вы можете только скомпилировать исходный код файлы (которые могут #include заголовочные файлы), чтобы создать объектные файлы.

    Заголовочный файл, которым вы #include можете быть предварительно скомпилированный заголовочный файл, для компиляторов, поддерживающих эту концепцию, с учетом ограничений, специфичных для компилятора на его использование (и, несмотря на название, предварительно скомпилированный заголовочный файл не скомпилирован : это не объектный файл).

    Компоновщик может связывать только объектные файлы и динамические библиотеки для создания исполняемого файла. Он может использовать объектные файлы напрямую или извлекать их из статической библиотеки.

    Ваша неудачная команда связывания:

    Показывает, что вы пытаетесь связать предварительно скомпилированный заголовок readFileByChars.h.gch . Линкер говорит:

    Потому что предварительно скомпилированный заголовок не является объектным файлом или статической или динамической библиотекой. Это не то, что понимает компоновщик.

    Исправьте параметры своего проекта, чтобы вы больше не проходили readFileByChars.h.gch в качестве входного линкера.

    Предположительно, вы прошли специальные действия сгенерировать предварительно скомпилированный заголовок readFileByChars.h.gch в вашем проекте Code :: Blocks. Если вы правильно следовали этой документации, вам больше ничего не нужно делать, не упоминает. Ваши другие параметры проекта не должны ничего сообщать компилятору или компоновщику о предварительно скомпилированном заголовке.

    Нет необходимости использовать предварительно скомпилированные заголовки, и, как вы видите, их правильное использование не является надежным и зависит от компилятора. Я бы посоветовал вам построить этот и другие проекты обычным способом, без предварительно скомпилированных заголовков, до тех пор, пока вы не столкнетесь с чрезмерно длительным временем компиляции, которое прекомпилированный заголовок может с пользой сократить.

    Вот как я решил эту проблему: 1. Если вы сначала запустите файл из кодовых блоков выхода из проекта. 2. Откройте файл отдельно (не открывайте файл проекта codeblocks!) И запустите.

    Реальный ответ: 1. Откройте диспетчер задач (Ctrl + Shift + Esc)
    2. перейти к деталям
    3. найдите имя проекта и завершите задачу (будет файл .exe с именем проекта)
    Выполнено!

    Источник

    15 причин, почему CodeBlocks не работает

    Я постоянно получаю письма о том, что CodeBlocks ведет себя как-то не так. В этой статьей рассмотрим самые популярные причины, почему CodeBlocks может неверно себя вести.

    1. Не хватает нужных компонентов (компилятора, отладчика, библиотек)

    Нужно понимать, что CodeBlocks — это просто каркас для подключения различных инструментов. Если вы просто скачаете пустой CodeBlocks с официального сайта и попытаетесь писать и отлаживать программу, то у вас ничего не получится. CodeBlocks не сможет запустить ни комплятор, ни отладчик. Все это нужно скачивать и устанавливать отдельно.

    Но тут будет новая проблема — проблема выбора. CodeBlocks поддерживает все существующие компиляторы Си, какой выбрать? То же относится к любому другому инструментарию: отладчикам, профайлерам, плагинам и т.д.

    Именно поэтому я и сделал сборку Си-экспресс, чтобы можно было сразу распаковать и работать. Все нужные компоненты уже установлены. Если вы точно знаете, что вам нужен другой компонент, то просто найдите и замените его на тот, который вам нужен.

    Решение: Скачайте сборку Си-экспресс.

    2. Неверно указаны пути к компонентам

    3. Символы кириллицы или пробелы в пути к программе CodeBlocks

    Есть старая проблема с тем, что инструменты программиста часто имеют проблемы с кодировками. Считается, что программист настолько крут, что сможет эту проблему решить самостоятельно. Но для новичков в программировании это оказывается непреодолимым препятствием. Новички часто устанавливают CodeBlocks:

    • или в «c:Program Files (x86)CodeBlocks»
    • или в папку типа «c:Я начинаю изучать программированиеCodeBlocks»

    4. Символы кириллицы или пробелы в пути к разрабатываемой программе

    Это следствие той же проблемы, что и в предыдущем случае. Программист нормально установил среду программирования, все работает, но вдруг какая-то новая программа отказывается компилироваться. Обычно описание ошибки выглядит как: «No such file or directory» при этом имя файла отображается в нечитаемой кодировке.

    Как правило, причина в том, что путь к проекту содержит символы кириллицы или пробелы. Например проект был размещен в каталоге с именем типа: «c:Новая папка».

    Решение: Создавайте проекты в папке «c:Work» или в любой другой папке, в пути к которой нет пробелов или кириллицы.

    5. Не все пункты меню активны

    Вы запустили CodeBlocks, но при этом некоторые пункты меню не активны. Например, иконки для отладки:

    Это происходит в том случае, если вы связали расширение «.c» с вызовом CodeBlocks. В этом случае среда работает как редактор исходного текста. Чтобы активировать все функции среды нужно открыть проект.

    Решение: Сначала запустите CodeBlocks, а затем откройте проект. Проект имеет расширение «.cbp».

    6. При запуске компилятора ничего не происходит

    Это следствие той же проблемы, что и в пункте 5. CodeBlocks запущен в режиме простого редактирования, поэтому не все функции работают. Для включения всех функций вы должны работать с проектом.

    Решение: Откройте проект или создайте новый.

    7. Программа работает из CodeBlocks, но если запустить ее отдельно, то она сразу закрывается

    8. CodeBlocks запускает предыдущую версию программы

    9. Компиляция проходит без ошибок, но программа не запускается

    10. Антивирус блокирует запись программы на диск

    Вы получаете следующее сообщение: «Permission denied».

    Решение: Отключите антивирус.

    11. Windows блокирует работу CodeBlocks

    Бывает так, что на одном компьютере CodeBlocks прекрасно работает, а при копировании на другой компьютер возникают ошибки. Это может быть следствием того, что Windows блокирует некоторые возможности программы.

    Решение. Запустите CodeBlocks от имени администратора
    Для этого нажмите правую кнопку мыши на файле codeblocks.exe

    12. Отладчик не останавливается на точке останова

    Вы поставили точку останова, но отладчик ее игнорирует. Это следствие ошибки №4. У вас символы кириллицы или пробелы в пути к программе.

    Решение: Создавайте проекты в папке «c:Work» или в любой другой папке, в пути к которой нет пробелов или кириллицы.

    13. Неверное указание пути к компилятору

    При запуске CodeBlocks появляется ошибка: «Can’t find compiler executable in your in your configured search path’s for GNU GCC COMPILER»

    Это означает, что в настройках неверное указание пути к компилятору. Для исправления зайдите в меню «Настройки — Compiler… — Программы» и нажмите кнопку «Автоопределение».

    Если CodeBlocks обнаружит компилятор, то можно работать. Если нет, то переустановите «Си-экспресс».

    14. Программа на GTK+ работает только в среде CodeBlocks

    Если запускать GTK-программу в среде Code::Blocks, то все работает, а если запустить exe-файл отдельно, то окна не появляются. Это означает, что программа не может найти GTK-библиотеки.

    Они есть в сборке «Си-экспресс» в папке GTK-LIB. Их нужно скопировать в папку с программой. Для разработки в папку Debug, а для релиза в папку Release.

    15. При запуске программы постоянно появляется окно консоли

    По умолчанию CodeBlocks запускает окно консоли.

    Для отключения окна консоли выберите в меню “Проект — Свойства — Цели сборки”. Выберите тип
    “Приложение с графическим интерфейсом” и нажмите “ok”.


    После этого внесите правку (например, добавьте пустую строку) и нажмите F9. Окна консоли не будет.

    Источник

  • I tried to search for that bug online, but all the posts are for C++.

    This is the message:

    test1.o: In function `ReadDictionary':
    /home/johnny/Desktop/haggai/test1.c:13: undefined reference to `CreateDictionary'
    collect2: error: ld returned 1 exit status
    make: *** [test1] Error 1
    

    It is super simple code, and I can’t understand what the problem is:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include "dict.h"
    #include "hash.h"
    
    
    pHash ReadDictionary() {
        /* This function reads a dictionary line by line from the standard input. */
        pHash dictionary;
        char entryLine[100] = "";
        char *word, *translation;
    
        dictionary = CreateDictionary();
        while (scanf("%s", entryLine) == 1) { // Not EOF
            word = strtok(entryLine, "=");
            translation = strtok(NULL, "=");
            AddTranslation(dictionary, word, translation);
        }
        return dictionary;
    }
    
    int main() {
        pHash dicti;
    ...
    

    Now this is the header file dict.h:

    #ifndef _DICT_H_
    #define _DICT_H_
    
    #include "hash.h"
    
    pHash CreateDictionary();
    ...
    
    #endif
    

    And here is the dict.c file:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include "hash.h"
    #include "dict.h"
    
    
    pHash CreateDectionary()
    {
        pHash newDict;
        newDict = HashCreate(650, HashWord, PrintEntry, CompareWords, GetEntryKey, DestroyEntry);
        return newDict;
    }
    

    And if you want to check file hash.h:

    #ifndef _HASH_H_
    #define _HASH_H_
    
    // Type definitions //
    typedef enum {FAIL = 0, SUCCESS} Result;
    typedef enum {SAME = 0, DIFFERENT} CompResult;
    
    typedef struct _Hash Hash, *pHash;
    
    typedef void* pElement;
    typedef void* pKey;
    
    // Function types //
    typedef int (*HashFunc) (pKey key, int size);
    typedef Result (*PrintFunc) (pElement element);
    typedef CompResult (*CompareFunc) (pKey key1, pKey key2);
    typedef pKey (*GetKeyFunc) (pElement element);
    typedef void (*DestroyFunc)(pElement element);
    ...
    
    // Interface functions //
    
    #endif
    

    Maybe it will be easier if I give you the files here?

    Anyway, I will be happy for tips on how to understand the problem.

    I tried to search for that bug online, but all the posts are for C++.

    This is the message:

    test1.o: In function `ReadDictionary':
    /home/johnny/Desktop/haggai/test1.c:13: undefined reference to `CreateDictionary'
    collect2: error: ld returned 1 exit status
    make: *** [test1] Error 1
    

    It is super simple code, and I can’t understand what the problem is:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include "dict.h"
    #include "hash.h"
    
    
    pHash ReadDictionary() {
        /* This function reads a dictionary line by line from the standard input. */
        pHash dictionary;
        char entryLine[100] = "";
        char *word, *translation;
    
        dictionary = CreateDictionary();
        while (scanf("%s", entryLine) == 1) { // Not EOF
            word = strtok(entryLine, "=");
            translation = strtok(NULL, "=");
            AddTranslation(dictionary, word, translation);
        }
        return dictionary;
    }
    
    int main() {
        pHash dicti;
    ...
    

    Now this is the header file dict.h:

    #ifndef _DICT_H_
    #define _DICT_H_
    
    #include "hash.h"
    
    pHash CreateDictionary();
    ...
    
    #endif
    

    And here is the dict.c file:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include "hash.h"
    #include "dict.h"
    
    
    pHash CreateDectionary()
    {
        pHash newDict;
        newDict = HashCreate(650, HashWord, PrintEntry, CompareWords, GetEntryKey, DestroyEntry);
        return newDict;
    }
    

    And if you want to check file hash.h:

    #ifndef _HASH_H_
    #define _HASH_H_
    
    // Type definitions //
    typedef enum {FAIL = 0, SUCCESS} Result;
    typedef enum {SAME = 0, DIFFERENT} CompResult;
    
    typedef struct _Hash Hash, *pHash;
    
    typedef void* pElement;
    typedef void* pKey;
    
    // Function types //
    typedef int (*HashFunc) (pKey key, int size);
    typedef Result (*PrintFunc) (pElement element);
    typedef CompResult (*CompareFunc) (pKey key1, pKey key2);
    typedef pKey (*GetKeyFunc) (pElement element);
    typedef void (*DestroyFunc)(pElement element);
    ...
    
    // Interface functions //
    
    #endif
    

    Maybe it will be easier if I give you the files here?

    Anyway, I will be happy for tips on how to understand the problem.

    • Index
    • » Programming & Scripting
    • » CodeBlocks+MinGW86_64 Cross Compiler: ld returns 1 exit status.

    Pages: 1

    #1 2016-05-17 06:02:38

    kudykennedy
    Member
    Registered: 2015-04-11
    Posts: 21

    CodeBlocks+MinGW86_64 Cross Compiler: ld returns 1 exit status.

    Hello, I am creating a GUI for my science project, using FLTK.
    The CodeBlocks default «GNU GCC Compiler» works fine.
    Then I wanted to compile exe for my program for Windows use.
    Add new compiler… check
    Directories set to /usr/x86_64-w64-mingw32/include (compiler), /usr/x86_64-w64-mingw32/lib (linker) and /usr/x86_64-w64-mingw32/include (resource compiler)
    Toolchains executables set to x86_64-w64-mingw32-gcc, x86_64-w64-mingw32-g++, x86_64-w64-mingw32-g++, x86_64-w64-mingw32-g++.
    Rebuild…from no error to

    ||=== Build: Debug in cap2_gui (compiler: cross_windows) ===|
    ../../../../../home/kudy/Downloads/fltk-1.3.3/FL/Fl_Widget.H||In member function ‘void Fl_Widget::callback(void (*)(Fl_Widget*, long int), long int)’:|
    ../../../../../home/kudy/Downloads/fltk-1.3.3/FL/Fl_Widget.H|576|warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]|
    ../../../../../home/kudy/Downloads/fltk-1.3.3/FL/Fl_Widget.H||In member function ‘void Fl_Widget::argument(long int)’:|
    ../../../../../home/kudy/Downloads/fltk-1.3.3/FL/Fl_Widget.H|598|warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]|
    ../../../../../home/kudy/Downloads/fltk-1.3.3/FL/Fl_Widget.H||In member function ‘void Fl_Widget::do_callback(Fl_Widget*, long int)’:|
    ../../../../../home/kudy/Downloads/fltk-1.3.3/FL/Fl_Widget.H|848|warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]|
    ../../../../../home/kudy/Downloads/fltk-1.3.3/FL/Fl_Menu_Item.H||In member function ‘void Fl_Menu_Item::callback(void (*)(Fl_Widget*, long int), long int)’:|
    ../../../../../home/kudy/Downloads/fltk-1.3.3/FL/Fl_Menu_Item.H|243|warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]|
    ../../../../../home/kudy/Downloads/fltk-1.3.3/FL/Fl_Menu_Item.H||In member function ‘void Fl_Menu_Item::argument(long int)’:|
    ../../../../../home/kudy/Downloads/fltk-1.3.3/FL/Fl_Menu_Item.H|267|warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]|
    ../../../../../home/kudy/Downloads/fltk-1.3.3/FL/Fl_Menu_Item.H||In member function ‘void Fl_Menu_Item::do_callback(Fl_Widget*, long int) const’:|
    ../../../../../home/kudy/Downloads/fltk-1.3.3/FL/Fl_Menu_Item.H|397|warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]|
    ld||unrecognized option '-z'|
    ||error: ld returned 1 exit status|
    ||=== Build failed: 2 error(s), 6 warning(s) (0 minute(s), 3 second(s)) ===|

    They are mostly warning from FLTK.
    But THIS:

    ld||unrecognized option '-z'|
    ||error: ld returned 1 exit status|

    stops me from rebuilding it, thus cannot have EXE file.
    What is this? Searching gives me no answer.

    #2 2016-05-17 06:24:30

    kudykennedy
    Member
    Registered: 2015-04-11
    Posts: 21

    Re: CodeBlocks+MinGW86_64 Cross Compiler: ld returns 1 exit status.

    Some more info: the rebuild code from codeblocks:

    x86_64-w64-mingw32-g++ -I/usr/include/freetype2 -march=x86-64 -mtune=generic -O2 -pipe -fstack-protector-strong -fvisibility-inlines-hidden -D_LARGEFILE_SOURCE -D_LARGEFILE64_SOURCE -D_THREAD_SAFE -D_REENTRANT -g -I../../../../../home/kudy/Downloads/fltk-1.3.3 -I/usr/x86_64-w64-mingw32/include -c /media/DATA/Projects/FLTK/cap2_gui/main.cpp -o obj/Debug/main.o

    the sucessful default rebuild (before cross compiling):

    g++ -I/usr/include/freetype2 -march=x86-64 -mtune=generic -O2 -pipe -fstack-protector-strong -fvisibility-inlines-hidden -D_LARGEFILE_SOURCE -D_LARGEFILE64_SOURCE -D_THREAD_SAFE -D_REENTRANT -g -I../../../../../home/kudy/Downloads/fltk-1.3.3 -c /media/DATA/Projects/FLTK/cap2_gui/main.cpp -o obj/Debug/main.o
    g++ -L../../../../../home/kudy/Downloads/fltk-1.3.3/lib -o bin/Debug/cap2_gui obj/Debug/main.o  -Wl,-O1,--sort-common,--as-needed,-z,relro -lGL -lGLU -Wl,-O1,--sort-common,--as-needed,-z,relro -lGL -lGLU  ../../../../../usr/lib/libfltk_images.so ../../../../../usr/lib/libfltk_gl.so ../../../../../usr/lib/libfltk.so ../../../../../usr/lib/libfltk_forms.so

    Other linker options:

    `fltk-config --ldstaticflags`
    -lGL -lGLU

    remove these lines clears ld||unrecognized option ‘-z’| but still returns 1.

    Last edited by kudykennedy (2016-05-17 06:55:02)

    #3 2016-05-17 12:12:34

    kudykennedy
    Member
    Registered: 2015-04-11
    Posts: 21

    Re: CodeBlocks+MinGW86_64 Cross Compiler: ld returns 1 exit status.

    Using GNU GCC COMPILER, compile success:

    g++ -O2 -s -g  -c /media/DATA/Projects/FLTK/cap2_gui/main.cpp -o obj/Debug/main.o
    g++  -o bin/Debug/cap2_gui obj/Debug/main.o   /lib/libfltk.so /lib/libfltk_forms.so /lib/libfltk_gl.so /lib/libfltk_images.so /lib/libGL.so
    Output file is bin/Debug/cap2_gui with size 292.44 KB
    Process terminated with status 0 (0 minute(s), 1 second(s))
    0 error(s), 0 warning(s) (0 minute(s), 1 second(s))

    THEN USING CROSS COMPILER MINGW:

    i686-w64-mingw32-g++ -O2 -s -g -DWINVER=0x0400 -D__WIN95__ -D__GNUWIN32__ -DSTRICT -DHAVE_W32API_H -D__WXMSW__ -D__WINDOWS__ -I/usr/i686-w64-mingw32/include -I/home/kudy/Downloads/fltk-1.3.3 -c /media/DATA/Projects/FLTK/cap2_gui/main.cpp -o obj/Debug/main.o
    i686-w64-mingw32-g++ -L/usr/i686-w64-mingw32/lib -o bin/Debug/cap2_gui obj/Debug/main.o   /lib/libGL.so /lib/libfltk.so /lib/libfltk_forms.so /lib/libfltk_gl.so /lib/libfltk_images.so
    /lib/libGL.so: file not recognized: File format not recognized
    collect2: error: ld returned 1 exit status
    Process terminated with status 1 (0 minute(s), 2 second(s))
    1 error(s), 0 warning(s) (0 minute(s), 2 second(s))

    IT KEEPS SAYING THOSE .SO LIBRARIES I LINKED WAS IN WRONG FORMAT.
    They compile just fine with GNU GCC COMPILER!
    What is the difference ?!?!?

    Last edited by kudykennedy (2016-05-17 13:51:13)

    #4 2016-05-17 12:49:24

    Trilby
    Inspector Parrot
    Registered: 2011-11-29
    Posts: 27,833
    Website

    Re: CodeBlocks+MinGW86_64 Cross Compiler: ld returns 1 exit status.

    First, please calm down.  All caps and excessive punctuation/exclamation points are not needed.

    Second, you are linking to ELF shared objects for a win32 build.  You need to use the win32 dlls provided by the mingw packages.

    Also, is this any different from your other post or are you just cross posting the same problem?


    «UNIX is simple and coherent…» — Dennis Ritchie, «GNU’s Not UNIX» —  Richard Stallman

    #5 2016-05-17 12:58:23

    kudykennedy
    Member
    Registered: 2015-04-11
    Posts: 21

    Re: CodeBlocks+MinGW86_64 Cross Compiler: ld returns 1 exit status.

    Ok, sorry. Changed to x86_64 mingw. Sill the same problem. My g++ is 64, all of my so are 64, still wrong format.
    This only happens with those I need libraries. For a simple Hello World, no error, and .exe is created.
    Even .so files in usr/lib64 won’t work. So you are saying, I have to link to dll files, instead of those .so files ?

    x86_64-w64-mingw32-g++ -O2 -s -g -DWINVER=0x0400 -D__WIN95__ -D__GNUWIN32__ -DSTRICT -DHAVE_W32API_H -D__WXMSW__ -D__WINDOWS__ -I/usr/x86_64-w64-mingw32/include -I/home/kudy/Downloads/fltk-1.3.3 -c /media/DATA/Projects/FLTK/cap2_gui/main.cpp -o obj/Debug/main.o
    x86_64-w64-mingw32-g++ -L/usr/x86_64-w64-mingw32/lib -L/home/kudy/Downloads/fltk-1.3.3/lib -o bin/Debug/cap2_gui obj/Debug/main.o   /lib64/libGL.so /lib64/libfltk.so /lib64/libfltk_forms.so /lib64/libfltk_gl.so /lib64/libfltk_images.so
    /lib64/libGL.so: error adding symbols: File in wrong format
    collect2: error: ld returned 1 exit status
    Process terminated with status 1 (0 minute(s), 0 second(s))
    1 error(s), 0 warning(s) (0 minute(s), 0 second(s))

    #6 2016-05-17 13:20:02

    Trilby
    Inspector Parrot
    Registered: 2011-11-29
    Posts: 27,833
    Website

    Re: CodeBlocks+MinGW86_64 Cross Compiler: ld returns 1 exit status.

    kudykennedy wrote:

    So you are saying, I have to link to dll files, instead of those .so files?

    Yes.  i686 vs x86_64 is not the issue.  Windows does not use the same ELF format that linux does, so you cannot use linux *.so files, you need to link to windows libs which are .dll files.

    The mingw compiler handles this for you for the standard libraries, that’s why your hello-world example worked fine.  But as soon as you include other libs, you need to give the linker the path to the dlls.  In most cases you can use mingw’s pkg-config to help with this, so just like in a linux build you could specify LDFLAGS from `pkg-config —libs <lib1> <lib2>` you can use mingw’s pkg-config the same way.  I forget the exact path and name of mingw’s pkg-config but it follows similar naming conventions as the compilers.

    You would actually be fine with the i686 build though as any Windows system can still run Win32.  Not long ago 32-bit builds seemed to be the norm and encouraged as they could run on any windows system while win64 could only run on 64 bit systems.  This is still true, but 32 bit windows systems may be less common now.


    «UNIX is simple and coherent…» — Dennis Ritchie, «GNU’s Not UNIX» —  Richard Stallman

    #7 2016-05-17 13:34:32

    kudykennedy
    Member
    Registered: 2015-04-11
    Posts: 21

    Re: CodeBlocks+MinGW86_64 Cross Compiler: ld returns 1 exit status.

    Thanks, great. Some more questions though.
    1. I have to look for 32 bit / 64 .dll files for FLTK and LIBGL. Do you have a good source for these?
    2. What if I do not have Windows, can makefiles alone generate dll instead of .so? And how to achieve it?

    #8 2016-05-17 13:41:29

    Trilby
    Inspector Parrot
    Registered: 2011-11-29
    Posts: 27,833
    Website

    Re: CodeBlocks+MinGW86_64 Cross Compiler: ld returns 1 exit status.

    1) The mingw group in the AUR, or the mingw repository.  I don’t see fltk there though, so you might need to build that yourself.  See any of the hundreds of other mingw PKGBUILDs for a template on how to build it.  But in general, installing dependencies for mingw builds is just like installing dependencies for linux builds.  If you’d build a package for linux using gcc and libABC, then to build for windows you’d need mingw-gcc and mingw-libABC.  You cannot mix and match: your libraries must match the system targetted by the compiler.

    2) The dlls are the windows equivalent of .so files, you should not need to «generate» them, they are in the mingw packages for that lib — fltk again may be an exception, but you don’t need to do anything special to generate the dlls, just build and install a mingw fltk package.  A makefile alone cannot generate anything, but a makefile with a mingw cross compiler does compile for windows, that’s it’s whole purpose.

    I can’t give a complete step-by-step as I’m no longer cross compiling on this system, but frankly I think you may need to take a step back and start a bit smaller.  Use libs that are available already for mingw to get used to cross compiling.  Then once you get used to it, making PKGBUILDs for other libs like fltk will be trivial.  You could also just download the windows dlls from fltk’s upstream source and just drop them in your build directory — but this would seem a bit messy to me.  EDIT: maybe not, fltk does not seem to distribute a windows build from what I can (quickly) find, just the source code.


    «UNIX is simple and coherent…» — Dennis Ritchie, «GNU’s Not UNIX» —  Richard Stallman

    #9 2016-05-17 13:59:10

    kudykennedy
    Member
    Registered: 2015-04-11
    Posts: 21

    Re: CodeBlocks+MinGW86_64 Cross Compiler: ld returns 1 exit status.

    Thank you wholeheartedly, not only saying where I’m wrong but also clearing my head on the whole cross-compiling issue.
    Marked solved. Long way to go until I can fully get rid of using Windows. Again, thanks.

    #10 2016-05-17 15:08:04

    ewaller
    Administrator
    From: Pasadena, CA
    Registered: 2009-07-13
    Posts: 19,010

    Re: CodeBlocks+MinGW86_64 Cross Compiler: ld returns 1 exit status.

    Moderator:  As far as I can tell, you had two threads going on the same topic.  Even if the threads were different issues, the overreaching issue seemed to be cross compile link errors in a particular IDE  I think this is of narrow interest, so I went ahead and merged the threads to keep things tidy.


    Nothing is too wonderful to be true, if it be consistent with the laws of nature — Michael Faraday
    Sometimes it is the people no one can imagine anything of who do the things no one can imagine. — Alan Turing

    How to Ask Questions the Smart Way

    • Forum
    • Beginners
    • first time installation. getting error l

    first time installation. getting error ld. exe cannot find -lsprite

    I installed code blocks first time. I am using windows 10, code blocks version 20.03. When i am trying to compile code i am getting error:
    ld.exe cannot find -lsprite
    ld.exe cannot find -lbgi
    error : ld returned 1 exit status.
    I am running hello world code:

    #include <iostream>

    using namespace std;

    int main()
    {
    cout << «Hello world!» << endl;
    return 0;
    }

    Last edited on

    The code is valid. I don’t recommend using code blocks. Try Visual Studio. You can run code online while learning until you figure it out:

    cpp.sh

    I am using windows 10, code blocks version 20.03.

    Condolences.

    ld.exe cannot find -lsprite
    ld.exe cannot find -lbgi
    error : ld returned 1 exit status.

    When you install Code::Blocks in Windows, it usually takes along some version of the MinGw compiler.
    ld.exe is the MinGw linker.
    Those error say the linker cannot find the libraries ‘bgi’ and ‘sprite’.

    Browsing Internet, it seems bgi could be the “Borland Graphics Interface […] a graphics library bundled with several Borland compilers for the DOS operating systems since 1987” (Wikipedia), while sprite could be part of the SFML library.

    It looks like you want to link against those libraries, but you haven’t provided your compiler the proper information (the directories) to find them.

    #include <iostream>

    using namespace std;

    int main()
    {
    cout << «Hello world!» << endl;
    return 0;
    }

    I’m afraid if you don’t explain what you’re really trying to do, we can’t help you.

    I just want to know that why am i getting those errors and how to resolve them?

    I just want to know that why am i getting those errors and how to resolve them?

    You are getting those errors because you’re trying to link against the mentioned libraries the wrong way.
    Either you haven’t installed them, or their aren’t in the directories you specified to the compiler, or you missed to specify the directories.

    You can resolve those errors by providing the compiler the right information.

    Nah, lsprite is not SFML.

    OP, just make a new, empty project. Don’t use one of the existing project templates.

    Go into your project/build settings and remove any linker options.

    I tested my C:B 20.03 install, twice creating a new project. 1st using the Console application template wizard, 2nd time using the Empty project template.

    Both compiled C++ «Hello World» code without a problem.

    @gsmehta7, something about your installation is borked. I couldn’t even begin to try to guess what without a lot more information.

    You might try uninstalling C:B from your system, and deleting the install dir. Then follow the instructions for C:B here:
    https://www.learncpp.com/cpp-tutorial/installing-an-integrated-development-environment-ide/
    and
    https://www.learncpp.com/cpp-tutorial/writing-your-first-program/

    Good luck! I hope you get your problems solved.

    And if/when you can compile code in C:B successfully let us know what you did. That could help others in the future who have the same/similar problems.

    Topic archived. No new replies allowed.

    Why is the collect error ld returned exit status happeningThe collect2: error: ld returned 1 exit status error message is easily fixed by removing an existing executable file inside your document. It is possible to remove the existing file that is running in the background by accessing the thread tools inside your system. The complete process is easy to do and only consists of a couple of steps.

    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.

    Contents

    • Why Is the collect2: Error: Ld Returned 1 Exit Status Happening?
    • How To Fix This Error Inside Your Program
      • – Listing All the Possible Methods for Debugging This Error
      • – A Common Error in the Gem Native Extension
      • – Using the Debugging Library Syntax for the collect2 Error
      • – Facing This Error in Dev C++
    • FAQs
      • – What Is collect2 Exe?
      • – What Does Error 1d Returned 1 Exit Status Mean?
      • – How To Combine Two Files in C++?
    • Final Conclusion and Further Notes

    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:

    1. Create two separate C++ source files on your server.
    2. Both files should be saved inside the same location on the server.
    3. Open the Command Prompt tool and run the various commands from your files.
    4. The tool is going to merge the two separate source files together and comply their functions.
    5. 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

    How to fix collect error ld returned exit status errorWeb developers are constantly struggling with the collect2 error inside their syntax and are unable to debug it. Lucky for you, now you know all the details to remove this error from your document without affecting the rest of the syntax.

    • Author
    • Recent Posts

    Position is Everything

    Position Is Everything: Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL.

    Position is Everything

    vitalya199529

    0 / 0 / 1

    Регистрация: 12.02.2013

    Сообщений: 21

    1

    13.11.2013, 14:14. Показов 49261. Ответов 14

    Метки нет (Все метки)


    господа программисты, объясните мне в чем тут дело, я решил поиграться со счетчиком строк, но вот что то он не запускается

    C++
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    
    #include<iostream>
    using namespace std;
    int main()
    { double f, m;
    int counter;
    counter=0;
    for(f=1.0; f<=100.0; f++)
    {m=f/3.28;
    cout«f«"funt"«"ravno"«m«"metr"«endl;
    counter++;
    if (counter == 2)
    {cout«endl;
    counter=0;
    }
    }
    return 0;
    }

    ошибка
    C:Program FilesDev-CppMinGW64bincollect2.exe [Error] ld returned 1 exit status

    я видел тему на счет этой ошибки на форуме но внятного решения проблемы так и не увидел
    HELP
    p.s. Я ТОЛЬКО НАЧАЛ ИЗУЧАТЬ ПРОГРАММИРОВАНИЕ НА С++, поэтому пожалуйста не нужно давать сложных решений данной проблемы)

    __________________
    Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



    0



    castaway

    Эксперт С++

    4978 / 3085 / 456

    Регистрация: 10.11.2010

    Сообщений: 11,164

    Записей в блоге: 10

    13.11.2013, 14:15

    2

    Тут, и везде в остальном коде не кавычки должны быть, а два знака <

    C++
    1
    
    cout«f«"funt"«"ravno"«m«"metr"«endl;



    0



    vitalya199529

    0 / 0 / 1

    Регистрация: 12.02.2013

    Сообщений: 21

    13.11.2013, 14:17

     [ТС]

    3

    Цитата
    Сообщение от castaway
    Посмотреть сообщение

    Тут, и везде в коде не кавычки должны быть, а два знака <

    C++
    1
    
    cout«f«"funt"«"ravno"«m«"metr"«endl;

    ну так это и есть два знака << просто при копировании кода из devc++ они заменились на «
    я уже не первый раз это замечаю



    0



    Эксперт С++

    4978 / 3085 / 456

    Регистрация: 10.11.2010

    Сообщений: 11,164

    Записей в блоге: 10

    13.11.2013, 14:19

    4

    Ты букву Б на клавиатуре видишь?



    0



    0 / 0 / 1

    Регистрация: 12.02.2013

    Сообщений: 21

    13.11.2013, 14:21

     [ТС]

    5

    так что дело не в этом, у меня да же при всем желании не получается поставить этот знак « только << так, так что ошибка не в этом

    Добавлено через 45 секунд

    Цитата
    Сообщение от castaway
    Посмотреть сообщение

    Ты букву Б на клавиатуре видишь?

    у меня да же при всем желании не получается поставить этот знак « только << так, так что ошибка не в этом



    0



    Эксперт С++

    4978 / 3085 / 456

    Регистрация: 10.11.2010

    Сообщений: 11,164

    Записей в блоге: 10

    13.11.2013, 14:23

    6

    Ты в Microsoft Word программы пишешь?



    0



    vitalya199529

    0 / 0 / 1

    Регистрация: 12.02.2013

    Сообщений: 21

    13.11.2013, 14:23

     [ТС]

    7

    C++
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    
    #include<iostream>
    using namespace std;
    int main()
    { double f, m;
    int counter;
    counter=0;
    for(f=1.0; f<=100.0; f++)
    {m=f/3.28;
    cout<<f<<"funt"<<"ravno"<<m<<"metr"<<endl;
    counter++;
    if (counter == 2)
    {cout<<endl;
    counter=0;
    }
    }
    return 0;
    }

    вот так вот у меня код записан в деве

    Добавлено через 22 секунды

    Цитата
    Сообщение от castaway
    Посмотреть сообщение

    Ты в Microsoft Word программы пишешь?

    Dev C++



    0



    Эксперт С++

    4978 / 3085 / 456

    Регистрация: 10.11.2010

    Сообщений: 11,164

    Записей в блоге: 10

    13.11.2013, 14:25

    8

    В этой программе нет синтаксических ошибок. У меня она компилируется нормально.



    0



    0 / 0 / 1

    Регистрация: 12.02.2013

    Сообщений: 21

    13.11.2013, 14:26

     [ТС]

    9

    я могу скрин кинуть, только скажите как это сделать))



    0



    Почетный модератор

    Эксперт С++

    5850 / 2861 / 392

    Регистрация: 01.11.2011

    Сообщений: 6,905

    13.11.2013, 14:31

    10

    vitalya199529, перепишите код руками. Не копируйте. Руками. Это и полезно вам будет и ошибку устранит.



    0



    0 / 0 / 1

    Регистрация: 12.02.2013

    Сообщений: 21

    13.11.2013, 14:37

     [ТС]

    11

    проблема решилась сама собой после 100500 попытки запуска все заработало)



    0



    0 / 0 / 0

    Регистрация: 05.04.2014

    Сообщений: 5

    08.08.2015, 14:21

    12

    Надо в диспетчере задач убить процесс своей программы. и запускай



    0



    Don’t worry, be happy

    17781 / 10545 / 2036

    Регистрация: 27.09.2012

    Сообщений: 26,516

    Записей в блоге: 1

    08.08.2015, 14:28

    13

    Надо в диспетчере задач убить процесс своей программы. и запускай

    Он за два года еще из цикла не вышел



    4



    castaway

    08.08.2015, 14:28

    Не по теме:

    Цитата
    Сообщение от Croessmah
    Посмотреть сообщение

    Он за два года еще из цикла не вышел

    :D.



    0



    0 / 0 / 0

    Регистрация: 05.08.2019

    Сообщений: 3

    05.08.2019, 22:17

    15

    Он просто консоль забыл вырубить и все



    0



    Понравилась статья? Поделить с друзьями:
  • Error launching the game 0x00000002 не удается найти указанный файл
  • Error launching the editor the application path does not exist unity
  • Error launching the application please check the system requirements avx yakuza 3
  • Error launching pycharm failed to load jvm dll
  • Error launching libguestfs appliance