How to compile a C++ program via Terminal Mac - c++

I have a question on how to compile a C++ program in Terminal Mac. My program has a header file and a main file. I know that I can't compile both the header file and the main file. and just to compile the main file. I also know that I need to create a name for storing the compiled file. Here is my compile command that I used g++ -o execute1 main.cpp and I get this:
Undefined symbols for architecture x86_64:
"add(int, int)", referenced from:
_main in main-f2nZvj.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
How can I fix this? Any help will be greatly appreciated. If it helps, below is my code for the two files:
add.h:
int add(int x, int y);
main.cpp:
#include <iostream>
#include "add.h"
int main(){
using namespace std;
cout << "The sum of 9 and 9 is " << add(9, 9) << endl;
return 0;
}

You need an add.cpp file that implements your add() function, then you can compile the whole thing as:
$ g++ -Wall main.cpp add.cpp -o execute1

This line:
int add(int x, int y);
in your add.h just tells the compiler that somewhere, there's a function called add that takes two integers and returns an integer. Having this and this alone will let the compiler leave you alone when you use this add function in files that #include "add.h". The compiler doesn't have to know exactly what the function does, it just needs to know what parameters it accepts and what the function returns. It doesn't bother looking for the function body until it actually goes to compile the function.
In order for this to properly compile, you need to include a function body for your add function in add.cpp. Even just this will work:
int add(int x, int y) {
return 1;
}
This will allow the program to compile because now the compiler know what code it's supposed to execute when it gets to your call to the add function within main.
This will work, as a minimum, as a placeholder until you're ready to actually write the exact logic you want this function to contain. But until this function body exists, you won't be able to compile (unless you remove all the other references to the function).

Related

Defining function with arrays in different files

I want to define a function in a separate C++ file. The function takes in array as an argument.
These are my files.
selectionsort.cpp
#include "selectionsort.hpp"
int selectionsort(int a[]){
int length{};
length = std::size(a);
for(int i{0}; i < length; ++i){
int smallestIndex{i};
for(int j{i+1}; j < length; ++j){
if(a[j] < a[smallestIndex]){
smallestIndex = j;
};
};
std::swap(a[smallestIndex], a[i]);
};
return 0;
};
selectionsort.hpp
#ifndef selectionsort_hpp
#define selectionsort_hpp
int selectionsort(int []);
#endif /* selectionsort_hpp */
main.cpp
#include "io.hpp"
#include "monsters.hpp"
#include "selectionsort.hpp"
#include <iostream>
#include <iterator>
int main(){
int a[]{ -1, -100, 0, 10, 100, -2, 2, 10000, 45, -10000};
selectionsort(a);
std::cout << a[0] << '\n';
std::cout << a[1] << '\n';
return 0;
};
Xcode shows the following error when I run the program.
Undefined symbols for architecture x86_64:
"selectionsort(int*)", referenced from:
_main in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Undefined symbol: selectionsort(int*)
However if I put the function definition of selectionsort.cpp inside the main.cpp file, everything works perfectly. I dont understand what is the problem here.
Your .cpp file contains an error that should not compile. As such, I suspect you are not building it in your current setup at all. That would explain why the object code is not being linked into your application, and the linker is unsatisfied.
If you do separate compilation, i.e.
g++ a.cpp -c
g++ b.cpp -c
Now you have two object files, a.o and b.o. To produce a binary, you must link them together:
g++ a.o b.o -o myprogram
In your code you are trying to pass an array:
int selectionsort(int a[]){
int length{};
length = std::size(a);
...
And you simply can't do that. The array decays to a pointer when passed to a function, and you can't call std::size on a pointer. This won't compile, because it has lost array information about the argument (which was encoded in its array type) and cannot determine its size when it is just a pointer. It has NO IDEA how big your array is when inside the function. The only way you could make this work is to change the code and pass in the size of the array along with your array. This is a common need, so there are span classes out there, and one was added to c++20, which basically bundles a pointer and a size together and you might consider using one of those.
If you fix your build system to build all of your code, then you fix the c++ error above (including changing your header declaration to match), then you link all your object code together, that may fix the issue you're seeing.

Xcode: linker command failed with exit code 1 (use -v to see invocation) [C++]

I am running a c++ programs with multiple files (2)
goofing_around.cpp
add.cpp
goofing_around.cpp:
//
// goofing_around.cpp
// new
//
// Created by Chirag Maheshwari on 14/08/18.
// Copyright © 2018 Chirag Maheshwari. All rights reserved.
//
#include <iostream>
int add(int x,int y);
int doubleNumber(int n)
{
return 2*n ;
}
int main()
{
int x;
std::cout << "Enter the number to be doubled: ";
std::cin >> x;
std::cout << doubleNumber(x)<<std::endl;
std::cout << add(3,2) << std::endl;
return 0;
}
add.cpp:
#include <iostream>
int add(int x,int y){
return x+y;
}
And yet I get an error which goes like this:
duplicate symbol _main in:
/Users/chirag/Library/Developer/Xcode/DerivedData/new-hapneuayvrpdonefrpnervwkxysx/Build/Intermediates.noindex/new.build/Debug/new.build/Objects-normal/x86_64/goofing_around-5915963FFFEE024.o
/Users/chirag/Library/Developer/Xcode/DerivedData/new-hapneuayvrpdonefrpnervwkxysx/Build/Intermediates.noindex/new.build/Debug/new.build/Objects-normal/x86_64/goofing_around-93C433489854664D.o
ld: 1 duplicate symbol for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Edit: This was weird.The error was there even before I added the add.cpp file.But then I deleted the projects and tried again.And after rewriting all the code,and adding the add file,I deleted the .h file.But only this time it worked,with the exact same code,and including the same function prototype.I did not have to include the add.cpp files either.
Super weird,but does anyone know why?
The problem is that you are not linking well the add method. You have implemented it in add.cpp but you don't add the link to it in the main code. You should include another "include" in goofing_around.cpp, something like
#include "add.cpp";
It should work.
Another observation: there is no need to print the name of the method "add" in the main code, since these things are done in the header files (if you have any). If not, there no sense to write that since you can just link your main code to the add.cpp.

Problems linking static library to c++ project with MinGW

Edit: ***Sorry I realize there must have been some misunderstanding when posting this question, I want to specify that I DO realize this question was asked a few times, none of the answers work for me however***
I've been trying to link a simple static library test to one of my c++ projects, but I can't seem to get it quite right. I know that this is a very widespread topic and that a lot of people have already asked a similar question, but even after reading some of the answers, I still cannot, for the love of god, figure out what I am doing wrong.
My code is very simple, first I have a .cpp source file titled "Math.cpp" that looks like this:
#include "Math.h"
int max(int a, int b) {
return a > b ? a : b;
}
int min(int a, int b) {
return a < b ? a : b;
}
int floor(double a) {
return (int) a;
}
int ceil(double a) {
return (int) a + 1;
}
..And to go with that I made a header file called "Math.h" that looks like this:
#pragma once
int max(int, int);
int min(int, int);
int floor(double);
int ceil(double);
I then compile "Math.cpp" with the following command on cmd:
g++ -c Math.cpp -o Math.o
...and then compile it into a static library like so:
ar rcs libMath.a Math.o
After all of this I make a new c++ soure file titled "Main.cpp" that looks like this:
#include <iostream>
#include "Math.h"
int main() {
std::cout << max(9, 8) << std::endl;
return 0;
}
("Math.h" is in the same directory as "Main.cpp")
So finally in order to link "Main.cpp" with my static library ("libMath.a"), I use the following command in cmd:
g++ -o Main.exe Main.cpp -L. -lMath
however, at this point, it throws the following error:
C:\Users\zalmar\AppData\Local\Temp\ccmOnvyg.o:Main.cpp:(.text+0x18): undefined reference to `max(int, int)'
collect2.exe: error: ld returned 1 exit status
... I cannot figure out why it can't find the reference to the specific function. Some people appeared to have the same problem (here for example). Their solution was to declare the Main.cpp source file before declaring the library path. However, that was not the case for me, even though I made sure I was linking the library after the Main.cpp it still came up with the same error. I would greatly appreciate it if someone could point out anything I might be doing wrong because clearly I must be doing something wrong. Otherwise it might be a problem with my MinGW compiler, maybe?
I also want to re-mention that this is just a test library and I am fully aware that it might be a bit overkill to compile an entire static library from such a simple program. I am simply trying to figure out how to link libraries to my c++ projects...

Separate header file and its logic in c++ [duplicate]

This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 5 years ago.
Please make me understand how header files works in C++. I am using osx and g++ compiler. I have
main.cpp
#include<iostream>
#include "myfunc.hpp"
using namespace std;
int main() {
square(10);
return 0;
}
myfunc.hpp
#ifndef MYFUNC_HPP_
#define MYFUNC_HPP_
/*
void square(int x) {
std::cout << x * x << std::endl;
};
*/
void square(int);
#endif // MYFUNC_HPP_
myfunc.cpp
#include<iostream>
#include "myfunc.hpp"
using namespace std;
void square(int x) {
cout << x * x << endl;
}
Now when I am trying to compile using g++ main.cpp , its giving
Undefined symbols for architecture x86_64:
"square(int)", referenced from:
_main in main-088331.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Because it is not able to find the function definition of square that is defined in myfunc.cpp.
But, if I defined square function in header file, it works because now it finds the function definition.
I want to use the function defined in myfunc.cpp in main.cpp, so I am using the header file myfunc.hpp. How can I achieve this? Am I doing something wrong here? Maybe my concept is not that clear about headers since I am new to C++ programming.
When you call g++ main.cpp, the compiler will try to compile and link the program, yet for linking, it lacks the source- or object file containing the definition of square. So it could compile main.cpp based on the function prototype given in the header file, yet it cannot link then.
To just compile main.cpp write
g++ -c main.cpp
To compile and link the complete program write:
g++ main.cpp myfunc.cpp
For more details concerning programs comprising several translation units confer, for example, this link.

C++ compiler issue (?): can't pass arguments to functions in separate class files [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is an undefined reference/unresolved external symbol error and how do I fix it?
I recently started working on an interpreter in C++, but I got annoyed that vectors or arrays could not be passed to external class methods no matter what I tried and so I deleted everything I had worked on. As it turns out, I can't pass even an int to another class. I decided to give C++ another chance before resorting to C or Java, but the compiler still doesn't work as I would expect. Maybe I'm forgetting something simple about C++, as I haven't used it in a while, but this seems simple enough. My problem is: I can't pass arguments to methods in other classes when they're not defined in the same file. Here's what I'm trying to do:
Main: main.cpp
#include "myclass.h"
int main() {
MyClass test;
int n = test.add(25, 30);
return n;
}
Header: myclass.h
class MyClass {
public:
int add(int a, int b);
};
Class implementation: myclass.cpp
#include "myclass.h"
int MyClass::add(int a, int b) {
return a + b;
}
Compiling this with g++ main.cpp yields
/tmp/ccAZr6EY.o: In function main':
main.cpp:(.text+0x1a): undefined reference toMyClass::add(int, int)'
collect2: error: ld returned 1 exit status
What the heck am I doing wrong? Also, the compiler yells at me for the same thing even if my functions aren't parameterized, so it must be a problem with the header.
Any help is much appreciated - thanks!
You need to compile both files
g++ main.cpp myclass.cpp
If you only compile main.cpp, the compiler finds the declaration of MyClass::add in your header but the linker later fails to find an implementation of MyClass::add to jump to.