что такое gcc в visual studio
Статьи
Статьи / Перевод с Visual C++ на gcc
Перевод с Visual C++ на gcc
Перевод программы с Visual C++ на GCC.
(правила программирования программ на C++, которые должны компилироваться и под Visual Studio и под GCC)
#pragma once
#ifndef _MY_MODULE_
#define _MY_MODULE_ // это пишем в начале файла
// код нашего модуля/файла
#endif // это пишем в конце файла
Работа с типами
3) GCC (особенно под линуксом) строго относится к конвертации указателей разных типов.
Visual Studio на такую запись выдаст предупреждение, а gcc наверняка выдаст ошибку:
Код работает только в Visual Studio | Код работает в Visual Studio и gcc |
unsigned char * a; char * b = a; | unsigned char * a; char * b = (char*) a; |
Работа с шаблонами
4) GCC строго относится к шаблонам. Так выглядит запись в студии:
Код работает только в Visual Studio | Код работает в Visual Studio и gcc |
template class Base : public Shared < void do() < //. wchar_t * wcharBuff = (wchar_t *) allocateArray(10); //. > >; | template class Base : public Shared < void do() < //. wchar_t * wcharBuff = (wchar_t *) Shared :: allocateArray(10); //. > >; |
10) При объявлении шаблонов необходимо ставить пробел между std::vector @Тут должен быть пробел@>. Рассмотрим это на примере:
Код работает только в Visual Studio | Код работает в gcc |
template class T> class Vector : public std::vector > <> | template class T> class Vector : public std::vector > <> |
Макросы
7) Старайтесь в конце каждого файла ставить один символ окончания строки.
Это соответствует стандарту, а gcc очень строго следует стандарту. Иначе на каждый файл вы рискуете, получить примерно такое предупреждение:
In file included from
C:\Work\String\import\Modules.h:38,
from
C:\Work\String\src\Main.cpp:8:
C:\Work\String\Global.h:344:30:
warning: no newline at end of file
Линковка
8) В Visual C++ есть очень удобная вещь. Директива:
#pragma comment (lib, «имя_библиотеки.lib»)
Она говорит компилятору, чтобы он во время линковки подключил указанную библиотеку. Замечательная штука, но в GCC такой нет.
Все библиотеки в GCC нужно подключать прописывая их в командной строке компилятора. Пример:
Use any C++ Compiler with Visual Studio
Microsoft Visual Studio 2017 supports several C++ compilers to suit a wide variety of codebases. In addition to the Microsoft Visual C++ compiler that many of you are likely familiar with, Visual Studio 2017 also supports Clang, GCC, and other compilers when targeting certain platforms.
This post is intended to familiarize you with the variety of C++ compilers that are compatible with the Visual Studio IDE, and to understand when they might be applicable to use with your projects. Some compilers may be better suited to your needs depending on your project or target. Alternatively, you may be interested in checking out new language features, such as C++ Concepts, that are not available across all compilers without needing to leave the IDE.
You can select the compiler and corresponding toolset that will be used to build a project with the “Platform Toolset” property under General Configuration Properties for C++ projects. Any installed compilers that are applicable to your project type will be listed in the “Platform Toolset” dropdown.
Microsoft C++ Compiler (MSVC)
If you are targeting Windows, the Microsoft C++ compiler (MSVC) may be the way to go. This is the default compiler for most Visual Studio C++ projects and is recommended if you are targeting Windows.
Compiler options for the Microsoft C++ compiler.
Clang
You can use the Clang compiler with Visual Studio to target Android, iOS, and Windows.
If you are targeting Android, you can use the Clang/LLVM compiler that ships with the Android NDK and toolchain to build your project. Likewise, Visual Studio can use Clang running on a Mac to build projects targeting iOS. Support for Android and iOS is included in the “Mobile Development with C++” workload. For more information about targeting Android or iOS check out our posts tagged with the keywords “Android” and “iOS”.
If you are targeting Windows, you have a few options:
Compiler options for the Clang/C2 compiler.
It might make sense to use Clang/C2 if you want to bring a codebase that takes advantage of Clang’s language features to the Windows platform. Since the code generation and optimization is handled by the MSVC backend, binaries produced by Clang/C2 are fully compatible with binaries produced by MSVC. You can learn more about Clang/C2 from Clang with Microsoft Codegen – or check out the latest updates in posts tagged with the keyword “clang”.
If your project targets Linux or Android, you can consider using GCC. Visual Studio’s C++ Android development natively supports building your projects with the GCC that ships with the Android NDK, just like it does for Clang. You can also target Linux – either remotely or locally with the Windows Subsystem for Linux – with GCC.
Compiler options for GCC.
Check out our post on Visual C++ for Linux Development for much more info about how to use Visual Studio to target Linux with GCC. If you are specifically interested in targeting WSL locally, check out Targeting WSL from Visual Studio.
Closing
Visual Studio also makes use of the Edison Design Group (EDG) frontend to provide flexible IntelliSense regardless of whether you use MSVC, Clang, or GCC to build your code. Visual Studio gives you access to a wide range of choices when it comes to C++ compilers. This way you can make sure that as you develop your code, it continues to compile against all major compilers.
Install Visual Studio today and give it a try. Please let us know if we have missed any compilers you use, and share your feedback as we look forward to improving your C++ development experience.
How to use GCC with Microsoft Visual Studio?
I am creating a very large project (a few thousand lines) and so would rather not use Notepad++. An IDE would make it so much easier. I have experience with Microsoft Visual Studio and love it. Is there some easy way to use Cygwin’s GCC from within Microsoft Visual Studio?
Alternately, are there any other good Windows IDEs for GCC besides NetBeans and Eclipse? (I hate both of them with a passion.)
3 Answers 3
There are several ways to go here:
Option 1: Create a Custom Build Tool
So far as I know, no one has done this yet for GCC. And, doing it yourself requires writing COM code, which is probably too deep a pool to dive into just for a single project. You’d have to have a compelling reason to take this project on.
On the plus side, if you were looking to start an open source project, this sounds like a good one to me. I expect you’d quickly gather a big user base.
Option 2: Makefile Project
Start Visual Studio and say File > New Project.
In the Visual C++ section, select Makefile Project
Fill out the Makefile Project Wizard:
You can leave the Output (for debugging) field alone if you’ve named your executable after the project name and it lands where Visual Studio expects to find it.
You’ll be asked the same set of questions for the Release build. If you want to bother with separate debug and release builds, you’d make any changes here.
As ugly as this looks, it’s still easier than creating custom build tools. Plus, you say you need to port to Unix eventually, so you’re going to need that Makefile anyway.
Option 3: Cross-Platform Development
You say you want to port this program to Unix at some point, but that doesn’t mean you must use GCC on Windows now. It is quite possible to write your program so that it builds under Visual C++ on Windows and GCC/Makefiles on *ix systems.
There are several tools that make this easier. One very popular option is CMake, which is available as an installation time option in newer versions of Visual Studio. There are many alternatives such as SCons and Bakefile.
Как использовать GCC с Microsoft Visual Studio?
Я создаю очень большой проект (несколько тысяч строк) и так что бы не использовать Notepad++. IDE сделает это намного проще. У меня есть опыт работы с Microsoft Visual Studio и мне это нравится. Есть ли простой способ использовать GCC Cygwin из Microsoft Visual Studio?
альтернативно, есть ли другие хорошие идентификаторы Windows для GCC, кроме NetBeans и Eclipse? (Я страстно ненавижу их обоих.)
2 ответов
есть несколько способов отправиться сюда:
Вариант 1: Создайте пользовательский инструмент сборки
насколько я знаю, никто еще не сделал этого для GCC. И, делая это самостоятельно, требуется написать COM-код, который, вероятно, слишком глубок для погружения в бассейн только для одного проекта. У тебя должна быть веская причина, чтобы взяться за этот проект.
С другой стороны, если вы хотите начать проект с открытым исходным кодом, это звучит как хорошая для меня. Я ожидаю, что вы быстро соберете большую базу пользователей.
Вариант 2: Проект Makefile
запустите Visual Studio и скажите Файл > Новый проект.
в разделе Visual C++ выберите проект Makefile
не устанавливайте флажок, предлагающий проверить проект в систему управления версиями, если вы используете Visual Studio Express. Если вы не платите за Visual Studio, вы, вероятно, также решили не платить за дорогостоящие «решения» Microsoft, и VSE не поддерживает сторонние VCS плагины, такие как AnkhSVN на в Subversion.
заполните мастер проекта Makefile:
оставить выход (для отладки) только поле, если вы не делаете что-то странное, например, не называя исполняемый файл после имени проекта или помещая имя исполняемого файла где-то, кроме верхнего уровня проекта.
вам будет задан тот же набор вопросов для сборки выпуска. Если вы хотите возиться с отдельными сборками отладки и выпуска, вы должны внести любые изменения здесь.
как бы уродливо это ни выглядело, это все равно проще, чем создавать пользовательские инструменты сборки. Кроме того, вы говорите, что вам нужно портировать в Unix в конце концов, поэтому вам понадобится это Makefile в любом случае.
Вариант 3: Кросс-Платформенная Разработка
вы скажем, вы хотите перенести эту программу в Unix в какой-то момент, но это не означает, что вы должны использовать GCC в Windows сейчас. Вполне возможно написать вашу программу так, чтобы она строилась под Visual C++ на Windows и gcc/Makefiles на системах *ix.
есть даже несколько инструментов, которые делают это проще, создавая файлы VS project и Makefile S из одного общего источника. Я использую Bakefile, а CMake становится все более популярным в последние годы. проектов SCons также выполняет эту работу и, вероятно, также более популярен, чем Bakefile; он, безусловно, обновляется чаще.
Я запустил его с GCC и GDB с IntelliSense, используя собственные странные JSON-файлы MS. Когда-нибудь, кто-нибудь (вы?) напишет скрипт Gradle или Python для их генерации; пока примеры в интернете в документах кажется работать.
кажется, требуется три типа вещи JSON;
Есть ли разница между GCC(g++) и Visual Studio?
Есть пару вопросов от начинающего.
1 ответ 1
Есть пару вопросов от начинающего.
Вопросов не пара, а три. 🙂
Если программа корректно компилируется в VS, будет ли она корректно компилироваться в g++(GCC)?
Не факт, но при некоторых усилиях можно добиться, чтобы компилировалось и там и там.
Сама утилита make ничего не компилирует, make это система для сборки, которая использует внешний компилятор.
Если программа корректно компилируется в VS на Windows 10, будет ли она корректно компилироваться на Linux?
Опять же смотря какой компилятор Вы примените в Linux. Кстати, компилироваться может и будет, а работать не будет, так как системные вызовы в Windows и Linux разные.
Есть ли возможность проверить будет ли программа компилироваться в Linux и в g++(GCC)?
Конечно, такая возможность есть. Ставите VS и GCC и проверяете.
Не обязательно ставить Linux, чтобы проверить компилируемость Вашей программы под GCC. Есть порты GCC под Windows.
В связи с захватывающим спором коллег о природе утилиты make я не поленился и поглядел, как в Википедии определяется эта утилита. Вот что там написано:
make — утилита, автоматизирующая процесс преобразования файлов из одной формы в другую. Чаще всего это компиляция исходного кода в объектные файлы и последующая компоновка в исполняемые файлы или библиотеки.
Утилита использует специальные make-файлы, в которых указаны зависимости файлов друг от друга и правила для их удовлетворения. На основе информации о времени последнего изменения каждого файла make определяет и запускает необходимые программы.