Linux compile cpp files

C how to compile cpp file in linux

That message is not valid C++ code and is NOT commented out so of course it will cause compiler errors. Here we will see how to compile C++ program using GCC (GNU C Compiler).

How to compile a c++ program in Linux?

g++ is for C++, gcc is for C although with the -libstdc++ you can compile c++ most people don’t do this.

As the other answers say, use g++ instead of gcc .

You have to use g++ (as mentioned in other answers). On top of that you can think of providing some good options available at command line (which helps you avoid making ill formed code):

g++ -O4 -Wall hi.cpp -o hi.out ^^^^^ ^^^^^^ optimize related to coding mistakes 

For more detail you can refer to man g++ | less .

Walkthrough: Compile a C program on the command line, Enter notepad hello.c at the developer command prompt. In the Notepad alert dialog that pops up, choose Yes to create a new hello.c file in

How to compile and run C++ program using G++ on Ubuntu 18.04

In this video I am going to show How to Compile and Run C++ program Using G++ on Ubuntu Duration: 6:10

How to Compile and Run Execute C, C++ on Ubuntu

Transcript · Install and Run C++ in Visual Studio Code (Linux) · [Environment Setup 8
Duration: 4:37

How To Compile And Run C++ Program In Ubuntu Linux

how to compile and run c++ program in ubuntu linuxHow to compile and run a C++ program in
Duration: 3:05

Compiling a C++ program with GCC

Here we will see how to compile C++ program using GCC (GNU C Compiler). Let us consider, we want to compile this program.

Example

#include using namespace std; main()

If this is a C program, we can compile with GCC like below −

But if we put c++ filename in that area, it may generate some error.

Output

/tmp/ccf1KGDi.o: In function `main': 1325.test.cpp:(.text+0xe): undefined reference to `std::cout' 1325.test.cpp:(.text+0x13): undefined reference to `std::basic_ostream >& std::operator >(std::basic_ostream >&, char const*)' 1325.test.cpp:(.text+0x1d): undefined reference to `std::basic_ostream >& std::endl >(std::basic_ostream >&)' 1325.test.cpp:(.text+0x28): undefined reference to `std::ostream::operator<<(std::ostream& (*)(std::ostream&))' /tmp/ccf1KGDi.o: In function `__static_initialization_and_destruction_0(int, int)': 1325.test.cpp:(.text+0x58): undefined reference to `std::ios_base::Init::Init()' 1325.test.cpp:(.text+0x6d): undefined reference to `std::ios_base::Init::~Init()' collect2: error: ld returned 1 exit status $

This is not compilation error. This is linking error. To add the correct linker, we have to use –lstdc++ option.

Output

$ ./a.out Hello World. This is C++ program $

Compiling a C++ program with GCC, Compiling a C++ program with GCC - Here we will see how to compile C++ program using GCC (GNU C Compiler). Let us consider, we want to

Читайте также:  Raspberry pi linux source

Compile and run c++ program with own header files in linux

You don't link to hello.o in the command below:

Or for such simple program, just issue the command below:

g++ -o main main.cpp hello.cpp 

For ease of use, create a makefile, then you just run make:

helloprogram: hello.h hello.cpp main.cpp g++ -o helloprogram main.cpp hello.cpp clean: rm helloprogram 
g++ -o main -I Path2Hello main.cpp hello.cpp 

ps: -I option to specify an alternate include directory (for header files).

To compile and run a C language program, you need a C compiler. To setup a C language compiler in your Computer/laptop, there are two ways:

Download a full fledged IDE like Turbo C or Microsoft Visual C++, which comes along with a C language compiler. Or, you use any text editor to edit the program files and download the C compiler separately.

How can I compile and run C/C++ code in a Unix console or Mac, where the source file is foo.c, foo.cpp, etc., you don't even need a makefile. Make has enough built-in rules to build your source file into an executable

How do I compile a .cpp file on Linux?

You'll need to compile it using:

g++ inputfile.cpp -o outputbinary 

The file you are referring has a missing #include directive, if you also include that in your file, everything shall compile fine.

The compiler is telling you that there are problems starting at line 122 in the middle of that strange FBI-CIA warning message. That message is not valid C++ code and is NOT commented out so of course it will cause compiler errors. Try removing that entire message.

Also, I agree with In silico: you should always tell us what you tried and exactly what error messages you got.

Just type the code and save it in .cpp format. then try "gcc filename.cpp" . This will create the object file. then try "./a.out" (This is the default object file name). If you want to know about gcc you can always try "man gcc"

Walkthrough: Compiling a Native C++ Program on the Command Line, Enter notepad hello.cpp in the command prompt window. Choose Yes when Notepad prompts you to create a new file. This step opens a blank Notepad

Источник

LibreBay

Статьи про ОС Ubuntu. Языки программирования Си и C++.
Инструменты разработки и многое другое.

понедельник, 5 декабря 2016 г.

Как скомпилировать программу на C/C++ в Ubuntu

ubuntu terminal

Помню, когда я только начинал программировать, у меня возник вопрос: «Как скомпилировать программу на C в Ubuntu?» Для новичков это не легкая задача, как может показаться на первый взгляд.

Мой путь изучения C начался с бестселлера «Брайан Керниган, Деннис Ритчи, Язык программирования C, 2-е издание». Там рассказывается как скомпилировать программу в операционной системе Unix, но этот способ не работает в Linux. Авторы книги выкрутились, написав следующее:

В других системах это процедура будет отличаться. Обратитесь к справочнику или специалисту за подробностями.

Побуду специалистом 🙂 и расскажу в данной статье, как скомпилировать первые программы на C и заодно на C++ в терминале Ubuntu.

Текстовый редактор gedit

Для написания первых программ подойдет обычный, используемый по умолчанию в Ubuntu, текстовый редактор с подсветкой синтаксиса — gedit.

Запуск текстового редактора
Рис. 1. Запуск текстового редактора.

Первой программой по традиции является «Hello, World!», выводящее приветствие на экран:

#include int main(int argc, char **argv)

Печатаем или копируем текст программы в gedit и сохраняем в файл Hello.c , например, на рабочий стол. Не самое лучше место для сохранения, но это позволит рассмотреть случай, когда в имени директории содержится пробел.

Читайте также:  Ubuntu with linux generic
Программа hello, World!
Рис. 2. Программа hello, World.

Компиляция программы на C

Теперь запускаем терминал, можно через Dash, а можно с помощью горячих клавиш + + . Здесь в начале установим инструменты сборки, куда входят необходимые компиляторы gcc для языка C и g++ для языка C++:

sudo apt install build-essential

Для установки требуется ввести пароль, при вводе которого может сложиться впечатление, что ничего не происходит, но на самом деле терминал просто в целях безопасности не отображает символы.

Далее в терминале нам необходимо перейти в директорию, куда сохранили файл с текстом программы. Перемещение выполняется командой cd (англ. change directory — изменить каталог). Чтобы воспользоваться командой в начале пишется cd , затем через пробел путь , куда нужно перейти.

Для перехода на рабочий стол, команда будет следующей:

Обратите внимание на символ обратной косой черты \ в имени директории Рабочий стол . Обратная косая экранирует пробел, и сообщает команде cd , что пробел и следующие за ним символы являются частью имени. Символ ~ в начале пути обозначает путь до домашней папки пользователя.

Для просмотра содержимого директории применяется команда ls (сокращение от англ. list).

Работа в терминале
Рис. 3. Работа в терминале.

Команда компиляции для программы на C выглядит следующим образом:

  • gcc — компилятор для языка программирования C;
  • -Wall — ключ вывода всех предупреждений компилятора;
  • -o hello — с помощью ключа -o указывается имя выходного файла;
  • hello.c — имя нашего исходного файла, который компилируем.

В завершение запустим hello , вводом имени программы с префиксом ./ :

Префикс ./ сообщает терминалу о необходимости выполнить программу с заданным именем в текущем каталоге. (Точка — это условное название текущего каталога.)

Работа в терминале, продолжение
Рис. 4. Работа в терминале, продолжение.

Компиляция программы на С++

Программы на C++ компилируются аналогично, как и программы на C. «Hello, World!» на C++ можно написать так:

#include int main(int argc, char **argv)

Сохраняем текст программы в файл под именем hello2.cpp . Таким образом, команда компилирования будет иметь вид:

g++ -Wall -o hello2 hello2.cpp

Для запуска результата вводим в терминале:

Заключение

Данный способ позволяет скомпилировать программу лишь из одного файла с исходным кодом. Но этого вполне достаточно, чтобы начать изучение языков программирования C/C++ по книгам или по статьям в интернете.

  • Иванов Н. Н. — Программирование в Linux. Самоучитель. — 2-е издание;
  • Нейл Метьэ, Ричард Стоунс — Основы программирования в Linux: Пер. с англ. — 4-е издание;
  • Колисниченко Д. Н. — Разработка Linux-приложений.

Источник

How can I compile and run C/C++ code in a Unix console or Mac terminal?

where the source file is foo.c, foo.cpp, etc., you don’t even need a makefile. Make has enough built-in rules to build your source file into an executable of the same name, minus the extension.

Running the executable just built is the same as running any program - but you will most often need to specify the path to the executable as the shell will only search what is in $PATH to find executables, and most often that does not include the current directory ( . ).

So to run the built executable foo :

I didn't realize the builtin rules propagated to targets specified when invoking make. Learned something new today =)

"-bash: make: command not found"

@FabianAmran It refers to the current directory. The shell will look only in the directories listed in the $PATH environment variable for programs to execute unless a path is specified when running the program. . (current directory) is often not in $PATH for security reasons.

gcc main.cpp -o main.out ./main.out 

I used "gcc main.cpp -o main.out", and get this error, Undefined symbols for architecture x86_64: "std::__1::locale::use_facet(std::__1::locale::id&) const", . turns out the reason is, gcc default-links is libc. while using g++ will link with libstdc++. So use "g++ main.cpp -o main.out" may be better.

Читайте также:  Adobe acrobat reader on linux

About Undefined symbols for architecture x86_64 issue, I modify the command as follows: gcc -lstdc++ main.cpp -o main.out , and that works on my Mac. via link:stackoverflow.com/questions/11852568/…

This is the command that works on all Unix machines. I use it on Linux/Ubuntu, but it works in OS X as well. Type the following command in Terminal.app.

-o is the letter O, not zero

lab21 will be your executable file

iterative.cpp is your C++ file

After you run that command, type the following in the terminal to run your program:

All application execution in a Unix (Linux, Mac OS X, AIX, etc.) environment depends on the executable search path.

You can display this path in the terminal with this command:

On Mac OS X (by default) this will display the following colon separated search path:

So any executable in the listed directories can by run just by typing in their name. For example:

This runs /bin/cat and displays mytextfile.txt to the terminal.

To run any other command that is not in the executable search path requires that you qualify the path to the executable. So say I had an executable called MyProgram in my home directory on Mac OS X I can fully qualify it like so:

If you are in a location that is near the program you wished to execute you can qualify the name with a partial path. For example, if MyProgram was in the directory /Users/oliver/MyProject I and I was in my home directory I can qualify the executable name like this, and have it execute:

Or say I was in the directory /Users/oliver/MyProject2 and I wanted to execute /Users/oliver/MyProject/MyProgram I can use a relative path like this, to execute it:

Similarly if I am in the same directory as MyProgram I need to use a "current directory" relative path. The current directory you are in is the period character followed by a slash. For example:

To determine which directory you are currently in use the pwd command.

If you are commonly putting programs in a place on your hard disk that you wish to run without having to qualify their names. For example, if you have a "bin" directory in your home directory for regularly used shell scripts of other programs it may be wise to alter your executable search path.

This can be does easily by either creating or editing the existing .bash_profile file in your home directory and adding the lines:

Here the tilde (~) character is being used as a shortcut for /Users/oliver. Also note that the hash bang (#!) line needs to be the first line of the file (if it doesn't already exist). Note also that this technique requires that your login shell be bash (the default on Mac OS X and most Linux distributions). Also note that if you want your programs installed in ~/bin to be used in preference to system executables your should reorder the export statement as follows:

Источник

Оцените статью
Adblock
detector