Recompiling of c++ Source Files in a Project After Changing a Function - c++

In Visual C++, if I change what a function, class, struct, etc. does in a source file but not the corresponding prototype in its header file, will all source files that use the function, class, struct, etc. need to be recompiled?
For instance, if I initially have something like this:
//function.h
int function(int x, int y);
//function.cpp
int function(int x, int y){
return x+y;
}
//main.cpp
#include function.h
int main(){
int x=3
int y=2
std::cout<<function(x, y);
return 0;
}
And then I change function.cpp to this:
//function.cpp
int function(int x, int y){
return x*y;
}
Will I need to recompile main.cpp?

No, you don't need to recompile main, because the ABI (Application Binary Interface) of your function didn't change. However, you need to link your main application against the recompiled function.cpp.

Related

Visual Studio Code doesn't work with headers in the same project folder [duplicate]

I am using a simple function to add to integers, the class is declared in the Adder.h file as below
class Adder
{
public:
int add (int x, int y);
};
Then I have the Adder.cpp file which has the function definition
int add (int x, int y)
{
return x + y;
}
Then the main.cpp file which calls the function
# include "Adder.h"
# include <iostream>
using namespace std;
int main()
{
Adder adder1;
int result = adder1.add (2, 3);
cout << result;
}
I ran g++ -c Adder.cpp to create Adder.o file beforehand.
Then I ran g++ main.cpp but go the following error
main.cpp:(.text+0x2d): undefined reference to `Adder::add(int, int)'
Where am I going wrong?
In your second and final step, you didn't instruct the compiler (linker more exactly) to take into account Adder.o, so your final executable still doesn't know the implementation of Adder::add
Try, after getting Adder.o, to run g++ main.cpp Adder.o
Also, this may be relevant : Difference between compiling with object and source files
Also, if that is the complete code, as others have pointed out, in the Adder.cpp, you are just defining a simple function, not the one from the Adder class.
The problem is that you've defined a free function named add instead of defining a member function of class Adder. To define add as a member function we have to be in the scope of the class Adder which we can do by adding Adder:: before add as shown below:
Adder.cpp
//note the use of scope resolution operator ::
int Adder::add(int x, int y)//define a member function instead of a free function
{
return x + y;
}
In the above modified code, we are defining the member function add instead of the free function add.

How do you define a "Hello World" function in a seperate file in c++

and I apologize for asking a very basic question, but basically, I'm not able to wrap my head around include "fileImade.h"
I'm trying to write a main function, that's something like
int main()
{
int x = 5;
int y x 6;
std::cout << add(x, y) << std::endl;
}
where add() is defined in a separate .cpp file, and #include -ed in this one, (I'm doing this because I'm getting the point where my code is getting impractically large to do in a single file.), but my understanding is that you need a header file to... Glue your other files together, or I guess mortar them if the files are the bricks, but I absolutely cannot figure out how to make this work for the life of me.
(while using g++), should I tag -I? According to me googling, yes, according to my compiler output, no.
Should I write a header file and a .cpp files for the add() function? Apparantly, yes, or no, if I choose to write both files in the command line before the -o.
Should I include a forward declaration of the function in my main.cpp file? Again, according to the internet, yes, though that's not working terribly well for me.
So to my question: Can someone show me a main() function that calls a hello world() function in a separate file?
I'm honestly at my wits' end with this because all the guides seem to be on defining classes in header files, which, while useful, is a bit beyond the scope of what I'm attempting right now.
Thank you in advance for reading, and any advice offered.
The logic of the file separation may be imagined as:
(single file program)
/// DECLARATION of all functions needed in the main
int add(int x, int y); // declaration of add
///
int main()
{
std::cout << add(2, 3) << std::endl;
return 0;
}
/// IMPLEMENTATION of all functions needed in the main
int add(int x, int y)
{
return x + y;
}
The next you have to do is move all declarations to the headers and implementations to the cpps:
(separated files program)
/// add.h
#ifndef ADD_H /// https://en.wikipedia.org/wiki/Include_guard
#define ADD_H
int add(int x, int y);
#endif
/// main.cpp
#include "add.h"
int main()
{
std::cout << add(2, 3) << std::endl;
return 0;
}
/// add.cpp
#include "add.h"
int add(int x, int y)
{
return x + y;
}

different implementations for the same function (c/c++)

is it possible to have 2 (or more) different implementations for the same function declared in a header file?
I'll give an example - let's say we have a header file called common.h and 2 source files called src1.c and src2.c.
common.h
//lots of common function declarations implemented in some file common.c
int func(int a, int b);
src1.c
#include "common.h"
int func(int a, int b)
{
return a+b;
}
src2.c
#include "common.h"
int func(int a, int b)
{
return a*b;
}
let's say that I want each of the source file to use its local version of func(). is it possible to do so?
Yes, but if you attempted to link your main program against both src1 and src2 you would encounter an error because it wouldn't know which definition to use.
Headers are just ways for other code objects to be aware of what's available in other objects. Think of headers as a contract. Contracts are expected to be filled exactly one time, not zero or multiple times. If you link against both src1 and src2, you've essentially filled the int func(int a, int b); contract twice.
If you need to alternate between two functions with the same signature, you can use function pointers.
If you want each source file to only use its local implementation of func, and no other module uses those functions, you can remove the declaration from the header and declare them as static.
src1.c
static int func(int a, int b)
{
return a+b;
}
src2.c
static int func(int a, int b)
{
return a*b;
}
By doing this, each of these functions is only visible in the module it is defined in.
EDIT:
If you want two or more functions to implement an interface, you need to give them different names but you can use a function pointer to choose the one you want.
common.h
typedef int (*ftype)(int, int);
int func_add(int a, int b);
int func_mult(int a, int b);
src1.c
#include "common.h"
int func_add(int a, int b)
{
return a+b;
}
src2.c
#include "common.h"
int func_mult(int a, int b)
{
return a*b;
}
Then you can chose one or the other:
ftype func;
if (op=='+') {
func = func_add;
} else if (op=='*') {
func = func_mult;
...
}
int result = func(value1,value2);
If you compile it with each src[x].c, you'll be able to use it in any function of your .c
You can decide to not expose the function implementation to other translation units. In c, use keyword static before the function signature right where you implement the function (see code below); In C++, you can also use unnamed namespaces. By doing so, the linker will not give you an error, and each translation unit will use it's own implementation:
Suppose the following two translation units main.c and another.c. Both have their (private) implementation of int function(a,b), such that they yield different results when calling it:
extern void someOtherFeature();
static int function (a,b) {
return a+b;
}
int main(){
int x = function(1,2);
printf("main: function(1,2)=%d\n", x);
someOtherFeature();
}
// another.c:
#include <stdio.h>
static int function (a,b) {
return a*b;
}
void someOtherFeature() {
int x = function(1,2);
printf("someOtherFeature: function(1,2)=%d\n", x);
}
Output:
main: function(1,2)=3
someOtherFeature: function(1,2)=2
However, if both translation units exposed their implementations (i.e. both omitted keyword static, then the linker would report an error like duplicate symbol _function in:....
If you want each source file to use a local version of func, just put it in an unnamed namespace:
For example src1.C:
namespace
{
int func(int a, int b)
{
return a+b;
}
}
Then each source file will use its own version. You don't need to declare it in the header.
Note that your original code with the definitions at global namespace and declared in the header violates the one definition rule (two function definitions for the same name must always have the same definition), invoking undefined behavior, no diagnostic required.

can't use separate function files in eclipse

I am trying to declare the functions in separate files. In the code given below, my main() is defined in main.cpp and the int addition(int x, int y) is defined
in an another file named function.cpp.
My code:
main.cpp
#include "function.cpp"
#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
int a = 1;
int b = 15;
int sum = addition(a,b);
cout<<"\nSum = "<<sum<<"\n";
return 0;
}
fucntion.cpp
int addition(int x, int y)
{
int sum = x + y;
return sum;
}
But by using the above cod in Eclipse i am getting the following error. On the other hand, if i compile the code manually using make
through the linux terminal then, the same got works.
ERROR:
/home/eclipse_workspace/multiFiles/Debug/../funtion.cpp:9: multiple definition of `addition(int, int)'
./funtion.o:/home/eclipse_workspace/multiFiles/Debug/../funtion.cpp:9: first defined here
collect2: ld returned 1 exit status.
First of all it is not recommended to include .cpp files. You should create header (.h) with declarations, put implementations to .cpp, like now and wherever you need to use it just include.h . You should also read about avoiding multiple includes by adding #ifndef/#define/#endif.
Update:
#include works in pre compiling phase and more or less it means "paste here what you have in file ...". So it copies function from one file and pastes to main file then compiles it. After this it compiles also cpp file with your function - also ok. Now comes linking: because of previous steps and copy-paste it has two definitions (actually two symbols) which has same name - that is causing the error and that's why we have headers :)
First create a header file, for example Addition.h and declare the function name inside it. Then make a file Addition.cpp and write the addition function implementation and then include the Addition.h in your main.cpp file.
The concept of using a header file is that you can use it anywhere else and is not limited to your main.cpp program file.
So, in short
Addition.h
class Addition { public:
int addition(int a , int b); //function declaration
private: int result_; };
then in Addition.cpp
#include Addition.h
int Addition::addition(int x, int y) {
// function implementation
}
in main.cpp
#include <Addition.h>
int main()
{ int a=3, b=4, sum=0;
Addition objAdd; //creation of object for class Addition
sum = objAdd.addition(a,b);
}
Hope this helps in structuring your code.

Compiler Hiccup in C++ and with .o Files

I've been trying to compile a multi-file project, but every time I try to use a void in player.cpp, I keep getting this error message, which appears that the player.o that is created during compilation has the same definition of void player_action(...). When I tried to use a void in the other files, the same problem occurs, with their corresponding .o file. However, if I use structs in any of the files, no problems occurs, and no "multiple definition" error occurs. In the lines below is the error message the compiler is giving me.
obj\Debug\player.o: In function `Z13player_actioniii':
D:/Projects/Blackmail Mailman/player.cpp:13: multiple definition of `player_action(int, int, int)'
obj\Debug\main.o:D:/Projects/Blackmail Mailman/player.cpp:13: first defined here
This is the code from player.cpp I used:
#include "include_files.cpp"
struct player_struct
{
int x;
int y;
int previous_x;
int previous_y;
int mode;
};
void player_action(int x, int y, int mode)
{
SDL_Event event;
if (SDL_PollEvent(&event))
{
if (event.type == SDL_KEYDOWN)
{
switch(event.key.keysym.sym)
{
case SDLK_RIGHT:;
};
};
};
};
What could be wrong and how can I fix it? I'm using Codeblocks with Mingw and Windows XP. I already checked the other files and there aren't any extra definitions of void player_action().
You never #include .cpp files, rather the .h files only.
If you need to access void player_action() from several parts of your program you should make a header file myapi.h which contains the following:
//myapi.h
#ifndef MYAPI_HEADER
#define MYAPI_HEADER
void player_action(int x, int y, int mode);
/* more function declarations */
#endif
The file which defines the function will be like this:
//player.cpp
#include "myapi.h"
void player_action(int x, int y, int mode)
{
/*...*/
}
and the file which uses it will be like this:
//main.cpp
#include "myapi.h"
void GameCycle()
{
/*...*/
player_action(0,0,0);
/*...*/
}
Never include objects definitions with #include, unless you know what you are doing. And even if you do know, you should think twice before doing so. Always use include guards (#ifndef ... #define .. #endif) - this will prevent multiple inclusion of your header.
These are the basic recommendations. I have seen a good explanation of such stuff in B. Stroustrup's 'The C++ programming language'