Linking two .cpp and a .h files

后端 未结 8 893
小蘑菇
小蘑菇 2021-02-02 01:00

I\'m doing an exercise (from the third chapter of Thinking in C++) but I have a problem linking two .cpp files.

This is the exercise:

Create a h

相关标签:
8条回答
  • 2021-02-02 01:42

    You need to put an include like this:

    #include "headerfilename.h"
    

    at the very top of each .cpp document.

    0 讨论(0)
  • 2021-02-02 01:44

    It looks every beginner is going through this (including myself), in the main.cpp you include the .cpp file and not the .h,

    //func_ex_main.cpp
    #include "func_ex.cpp" // instead of .h
    #include <iostream>
    using namespace std;
    //etc...
    

    because the .cpp is linked to the header through the include in that .cpp file, and each function definition is linked to the deceleration through the :: notation before the definition.

    Remember that the default constructor and destructor in the .h file is declared and defined automatically (if you didn't override or overload it), which will result in a compile error if you just re-defined it in the .cpp file, so if you didn't want to override it just don't mention the constructor neither the destructor in neither the header nor source files.

    0 讨论(0)
  • 2021-02-02 01:44

    I use code::blocks too, and I had the same problem. The default setting in this IDE is that only one file is built. Here's what I did: project -> properties -> build targets -> Select the files related in the bottom right section. Hope this helps!

    0 讨论(0)
  • 2021-02-02 01:52
    gcc -c func_ex.cpp -o func_ex.o
    gcc func_ex_main.cpp func_ex.o -o func_ex_main
    
    0 讨论(0)
  • 2021-02-02 01:54

    First of all, how can you have func1(), func2(), func3() without having a return statement. Try to put your header body inside these (#include guards) :

    #ifndef func_ex.h
    #define func_ex.h
    /* your code */
    
    #endif 
    
    0 讨论(0)
  • 2021-02-02 01:59

    It sounds like the file is not finding the functions appropriately. Is the header file included in both files? You can include it like:

    #include "myheader.h"
    

    Did you make sure to compile both files together? Such as:

    gcc -o myprogram file1.cpp file2.cpp

    0 讨论(0)
提交回复
热议问题