g++ output: file not recognized: File format not recognized

后端 未结 3 1396
名媛妹妹
名媛妹妹 2020-12-10 10:12

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 i

相关标签:
3条回答
  • 2020-12-10 10:48

    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

    0 讨论(0)
  • 2020-12-10 10:59

    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).

    0 讨论(0)
  • 2020-12-10 11:00

    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
    
    0 讨论(0)
提交回复
热议问题