I keep getting the following error when I try to compile an example program from C++ how to program, Deitel and Deitel. I used g++ Fig11_05.cpp -o Fig11_05
I spent hours trying to solve this problem by looking up the Internet and particularly stackoverflow, but with no avail!
I tried using different command line arguments such as -libstd=libc++, -std=c++11, -std=c++14
the error I keep getting is as this:
Undefined symbols for architecture x86_64:
"operator<<(std::__1::basic_ostream >&, PhoneNumber const&)", referenced from:
_main in Fig11_05-1f04bd.o
"operator>>(std::__1::basic_istream >&, PhoneNumber&)", referenced from:
_main in Fig11_05-1f04bd.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
The result of g++ -v:
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk/usr/include/c++/4.2.1
Apple LLVM version 8.0.0 (clang-800.0.42.1)
Target: x86_64-apple-darwin15.6.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
The codes:
// Fig. 11.3: PhoneNumber.h
// PhoneNumber class definition
#ifndef PHONENUMBER_H
#define PHONENUMBER_H
#include <iostream>
#include <string>
class PhoneNumber
{
friend std::ostream& operator<<(std::ostream&, const PhoneNumber&);
friend std::istream &operator>>(std::istream&, PhoneNumber&);
private:
std::string areaCode; // 3-digit area code
std::string exchange; // 3-digit exchange
std::string line; // 4-digit line
}; // end class PhoneNumber
#endif
// Fig. 11.4: PhoneNumber.cpp
// Overloaded stream insertion and stream extraction operators
// for class PhoneNumber.
#include <iomanip>
#include "PhoneNumber.h"
using namespace std;
// overloaded stream insertion operator; cannot be
// a member function if we would like to invoke it with
// cout << somePhoneNumber;
ostream& operator<<(ostream& output, const PhoneNumber& number)
{
output << "Area Code: " << number.areaCode << "\nExchange: "
<< number.exchange << "\nLine: " << number.line << "\n"
<< "(" << number.areaCode << ") " << number.exchange << "-"
<< number.line << "\n";;
return output; // enables cout << a << b << c;
} // end function operator<<
// overloaded stream extraction operator; cannot be
// a member function if we would like to invoke it with
// cin >> somePhoneNumber;
istream& operator>>(istream& input, PhoneNumber& number)
{
input.ignore(); // skip (
input >> setw(3) >> number.areaCode; // input area code
input.ignore(2); // skip ) and space
input >> setw(3) >> number.exchange; // input exchange
input.ignore(); // skip dash (-)
input >> setw(4) >> number.line; // input line
return input; // enables cin >> a >> b >> c;
} // end function operator>>
// Fig. 11.5: fig11_05.cpp
// Demonstrating class PhoneNumber's overloaded stream insertion
// and stream extraction operators.
#include <iostream>
#include "PhoneNumber.h"
using namespace std;
int main()
{
PhoneNumber phone; // create object phone
cout << "Enter phone number in the form (123) 456-7890:" << endl;
// cin >> phone invokes operator>> by implicitly issuing
// the global function call operator>>( cin, phone )
cin >> phone;
cout << "\nThe phone number entered was:\n";
// cout << phone invokes operator<< by implicitly issuing
// the global function call operator<<( cout, phone )
cout << phone << endl;
} // end main
Note: I recently installed then uninstalled CUDA toolkit 8. I needed a newer version of Xcode, so I installed Xcode the newest version 8.2.1, and kept the old version in a different directory just in case. I don't think the problem is with the installation of Xcode though. Also when I installed CUDA I had to set DYLD_LIBRARY_PATH to a directory. However, it might not be the source of the problem! I am just trying to help you figure out the problem to help me fix it :)
Thank you in advance! You are such a good community!
Your attempt to build the program:
g++ Fig11_05.cpp -o Fig11_05
is unsuccessful because you have neglected to compile and link into the
program the code that contains the definitions of the functions:
std::ostream& operator<<(std::ostream& output, const PhoneNumber& number)
and:
std::istream& operator>>(std::istream& input, PhoneNumber& number)
which are called by your program. That is why the linker says:
Undefined symbols for architecture x86_64:
"operator<<(std::__1::basic_ostream >&, PhoneNumber const&)", referenced from: _main in Fig11_05-1f04bd.o
"operator>>(std::__1::basic_istream >&, PhoneNumber&)", referenced from: _main in Fig11_05-1f04bd.o
...
Do this instead:
g++ Fig11_05.cpp PhoneNumber.cpp -o Fig11_05
Or to spell out the process in full:-
Compile source file Fig11_05.cpp to object file Fig11_05.o:
$ g++ -o Fig11_05.o -c Fig11_05.cpp
Compile source file PhoneNumber.cpp to object file PhoneNumber.o:
$ g++ -o PhoneNumber.o -c PhoneNumber.cpp
Link the object files Fig11_05.o and PhoneNumber.o into program Fig11_05
$ g++ -o Fig11_05 Fig11_05.o PhoneNumber.o
You can then run:
./Fig11_05
Here is a fairly good beginner's tutorial
about building C or C++ programs with GCC.
Related
This question already has answers here:
Compiling a C++ program with GCC
(9 answers)
Closed 2 years ago.
I just installed openMP just running
brew install gcc
Then I compiled my code using
gcc-10 -o task -fopenmp task.c
However I got the error message:
Undefined symbols for architecture x86_64: "_main", referenced from: implicit entry/start for main executable ld: symbol(s) not found for architecture x86_64 collect2: error: ld returned 1 exit status
my code is:
1. #include <omp.h>
2. #include <iostream>
3. using namespace std;
4.
5. #define TAMA_NTHREADS 4
6.
7.
8. int main (int argc, const char * argv[]){
9.
10.
11. int nProcessors = omp_get_max_threads();
12.
13. cout<<"Numero di core disponibili: " << nProcessors << endl;
14.
15. omp_set_num_threads(nProcessors);
16.
17. cout << "Numero thread fuori pragma: " << omp_get_num_threads() << endl;
18.
19. #pragma omp parallel
20. {
21. cout << endl <<"Numero di thread in pragma: " << omp_get_num_threads() << endl;
22. cout << "Sono il thread numero: " << omp_get_thread_num();
23. cout << " E ti saluto! " << endl;
24. }
25.
26. exit(0);
27.}
May someone help me please?
"That's C++ code that you are trying to compile as C. Rename the file to task.cc and use g++-10 instead".
Hirsto this solved the problem thank you. Anyway it works even if I do not rename the file.
I am trying to code a very simple class in C++11 but I am getting the compiler error 'Undefined symbols for architecture x86_64'. What does it mean? How do I deal with it?
I am using Visual Studio Code for MacOS and the compiler Clang-8 (updated 2 days ago).
Here are the 3 files I have written so far:
*------------------------------------------------------------------*/
class Point
{
// Type declaration statements for data members
private:
double xCoord, yCoord; // Class atributes
public:
// Declaration statements for class methods
// Constructors for Point class
Point(); // Default constructor
Point(double x, double y); // Parameterized constructor
};
/*------------------------------------------------------------------*/
/*------------------------------------------------------------------*/
#include "Point.h" // Required
#include<iostream> // Required for cout
using namespace std;
// Default constructor
Point::Point()
{
cout << "Constructing point object, default: \n";
cout << "Initializing to zero" << endl;
xCoord = 0.0;
yCoord = 0.0;
}
// Parameterized constructor
Point::Point(double x, double y)
{
// Input paraneters x and y
cout << "Constructing point object, parameterized: \n";
cout << "Input parameters: " << x << "," << y << endl;
xCoord = x;
yCoord = y;
}
/*------------------------------------------------------------------*/
/*------------------------------------------------------------------*/
#include<iostream>
#include "Point.h"
using namespace std;
int main()
{
// Declare and initialize objects
cout << "In main, declare p1... " << endl;
Point p1;
cout << "\nIn main, declare p2... " << endl;
Point p2{1.5, -4.7};
return 0;
}
/*------------------------------------------------------------------*/
The full error message is:
Undefined symbols for architecture x86_64:
"Point::Point(double, double)", referenced from:
_main in cpp14test-15cf25.o
"Point::Point()", referenced from:
_main in cpp14test-15cf25.o
ld: symbol(s) not found for architecture x86_64
clang-8: error: linker command failed with exit code 1 (use -v to see invocation)
The terminal process terminated with exit code: 1
i have written this small piece of Code for testing purposes:
#include <iostream>
#include "SDL2/SDL.h"
int main(int argc, char* argv[]) {
if (SDL_Init(SDL_INIT_EVERYTHING) != 0) {
printf("Unable to initialize SDL: %s\n", SDL_GetError());
return 1;
}
// Betriebssystem ermitteln
std::string PlatFormString;
PlatFormString = SDL_GetPlatform();
std::cout << PlatFormString << "\n";
// Separator ermitteln
char Separator = '/';
if (PlatFormString == "Windows") {
Separator = '\\';
}
std::cout << "Separator: " << Separator << "\n";
// Installationspfad ermitteln
std::string InstallPath;
InstallPath = SDL_GetBasePath();
std::cout << InstallPath << "\n";
// Benutzerverzeichnis ermitteln
char* UserPath;
UserPath = SDL_GetPrefPath("TFF", "Blaster");
if (UserPath == nullptr) {
std::cout << "No Userpath aviable !! \n";
}
else {
std::cout << UserPath << "\n";
}
SDL_Quit();
return 0;
};
Under Linux eerthing works fine.
But under Windows, i am getting these strange errors ...
-------------- Build: Debug in Test (compiler: GNU GCC Compiler)---------------
g++.exe -LD:\mingw64 -LD:\mingw64\bin -LD:\mingw64\include -LD:\mingw64\include\SDL2 -LD:\mingw64\lib -o bin\Debug\Test.exe obj\Debug\src\Test.o -lmingw32 -lSDL2main -lSDL2 -lSDL2_image -lSDL2_mixer ..\..\mingw64\lib\libSDL2main.a ..\..\mingw64\lib\libSDL2.a
..\..\mingw64\lib\libSDL2.a(SDL_systimer.o): In function `timeSetPeriod':
/Users/slouken/release/SDL/SDL2-2.0.3-source/foo-x64/../src/timer/windows/SDL_systimer.c:58: undefined reference to `__imp_timeBeginPeriod'
/Users/slouken/release/SDL/SDL2-2.0.3-source/foo-x64/../src/timer/windows/SDL_systimer.c:52: undefined reference to `__imp_timeEndPeriod'
/Users/slouken/release/SDL/SDL2-2.0.3-source/foo-x64/../src/timer/windows/SDL_systimer.c:58: undefined reference to `__imp_timeBeginPeriod'
and so on. I dont know whats going on there. Can anyone help ?
I#m using Codeblocks 13.12, minGW64 (4.8.1), SDL 2.0.3 and Windows 7 64bit
You need to link against winmm.lib.
Try adding
#pragma comment(lib, "winmm.lib")
to your source.
I am posting this about a year later but for the future searchers here is the solution. Replace libSDL2.a with libSDL2.dll.a and it will compile just fine. The issue has something to do with dynamic and static linking with a windows machine or something I personally do I understand it completely but it works.
I came across the solution by reading this article: http://tech.yipp.ca/sdl/how-to-fix-libsdla-undefined-reference/
However this goes on a whole other solution I read between the lines or more particularly.
This is a really a rare problem that would occur only when you try to link with libSDL.a static library instead of the dynamic library SDL.dll. Then you have to add those library that SDL.dll normally links against which are the three above.
I use Xcode 4.5.2 and I wonna use Boost, but I got some problems.
In Build Setting, if I choose libc++ (LLVM C++ standard library with C++11 support), I will get the error messgae "Apple Mach-O Linker (ld) Error".
Just like this:
Undefined symbols for architecture x86_64:
"boost::filesystem::path_traits::dispatch(boost::filesystem::directory_entry const&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >&, std::__1::codecvt<wchar_t, char, __mbstate_t> const&)"
referenced from:
boost::filesystem::path::path<boost::filesystem::directory_entry>(boost::filesystem::directory_entry const&, boost::enable_if<boost::filesystem::path_traits::is_pathable<boost::decay<boost::filesystem::directory_entry>::type>, void>::type*) in test1 - inverted index.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
I include these two headers:
#include <boost/filesystem.hpp>
#include <boost/operators.hpp>
I also add these in Build Phases:
libboost_filesystem-mt.dylib
libboost_filesystem-mt.a
libboost_system-mt.dylib
libboost_system-mt.a
Code is here:
#include <boost/filesystem.hpp>
#include <boost/operators.hpp>
#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <set>
using namespace boost::filesystem;
std::map<std::string, std::set<int>> invertedIndex;
std::map<std::string, int> number;
bool check_char(const char in)
{
if((in>='A' && in<='Z') || (in>='a' && in<='z'))
return true;
else
return false;
}
int main() {
int con = 0;
std::string word;
path root("/Users/tomhu/Desktop/pro/data/");
std::string rootDirectory = root.native();
recursive_directory_iterator iter(root);
recursive_directory_iterator end;
for (; iter != end; ++iter)
{
if(is_regular_file(*iter))
{
std::string filename;
std::string directory(rootDirectory);
filename = iter->path().filename().native();
directory.append(filename);
std::ifstream fileIn(directory.c_str());
number[filename] = con;
if(!fileIn)
{
std::cerr << "File doesn't exist!" << std::endl;
exit(1);
}
while(fileIn>>word)
{
long po = 0;
if(!check_char(*(word.end()-1)))
word.pop_back();
transform(word.begin(),word.end(),word.begin(),::tolower);
if(word=="i")
word="I";
invertedIndex[word].insert(con);
}
}
}
std::cout << con << std::endl;
return 0;
}
!!!!!!!!
If I choose libstdc++ (GUN C++ standard library) in "Build Setting", I won't get any error message about Boost, but I can't use anything in C++11 Standard.
How to solve these problems?
See Why can't clang with libc++ in c++0x mode link this boost::program_options example? - Howard gave an excellent answer what's going wrong there.
And here is how you can recompile Boost for clang+libc++: How to compile/link Boost with clang++/libc++?
Hello I have a program with a global function that I'd like to customize at run time. Say, there are many versions of function foo() scattered over shared libraries. Now, based on system configuration detected at run time I'd like to use function from appropriate library.
File loader.cpp:
#include <dlfcn.h>
#include <iostream>
void __attribute__((weak)) foo();
int main(int argc, char *argv[])
{
void* dl = dlopen("./other.so", RTLD_NOW | RTLD_GLOBAL);
if (!dl)
{
std::cerr << dlerror() << std::endl;
return 1;
}
if (foo)
{
foo();
}
else
{
std::cerr << "No foo?" << std::endl;
}
dlclose(dl);
return 0;
}
File other.cpp:
#include <iostream>
void foo()
{
std::cout << "FOO!" << std::endl;
}
I compile the program with
g++ -Wall -fPIC -o loaded loader.cpp -ldl
g++ -Wall -fPIC -shared -o other.so other.cpp
However the weak symbol is not overriden. Any hints?
Symbols are resolved during load time of the image in which they are referenced. So when your executable is loaded, the reference to foo is already resolved. A later dlopen won't go and rebind all symbols - it only may affect later loads.
You'll have to use dlsym instead, or set LD_PRELOAD:
martin#mira:/tmp$ LD_PRELOAD=/tmp/other.so ./loaded
FOO!
You compiled the shared lib with g++.
As a result, the name of the function is mangled:
$ nm -S other.so |grep foo
0000000000000690 000000000000002e T _Z3foov
If you make it a pure C code and compile with
gcc instead of g++, you'll find it working as you expect.
Alternatively, define it as follows:
extern "C" void foo()
{
std::cout << "FOO!" << std::endl;
}