cmake_minimum_required(VERSION 3.16)
project(competitive_programming)
set(CMAKE_CXX_STANDARD 17)
add_executable(competitive_programming main.cpp)
As you see, I'm using C++ 17, and I want to use if initializer to keep the code neat,
if (auto result = right.find(second); result != right.end()){
result->second--;
}
But the compiler does not work as is supposed to be,
The readout seems as follows:
error: expected ')' before ';' token
if (auto result = right.find(item); result == right.end()){error: expected ')' before ';' token
if (auto result = right.find(item); result == right.end()){
My compiler is so, I guess:
g++ (x86_64-posix-seh, Built by strawberryperl.com project) 8.3.0
Try adding:
set(CMAKE_CXX_STANDARD_REQUIRED ON)
to your CMakeLists.txt. It makes sure that you are compiling with C++17 and it is not decayed to previous versions of compiler.
Related
Good day. Building program without using cmake
''' g++ -lpthread src/how2thread.cpp src/main.cpp -ggdb3 -std=c++17 -Wextra '''
produces no errors.
Although, using
'''
cmake . && make
'''
generates following build errors:
[ 25%] Building CXX object CMakeFiles/how2thread_lib.dir/src/how2thread.cpp.obj
D:/Scizzors/Dsktp/cpp/how2thread/src/how2thread.cpp: In member function 'how2thread::Request how2thread::Scheduler::get_request()':
D:/Scizzors/Dsktp/cpp/how2thread/src/how2thread.cpp:103:67: error: use of deleted function 'std::lock_guard<_Mutex>::lock_guard(const std::lock_guard<_Mutex>&) [with _Mutex = std::mutex]'
103 | auto m_lock = std::lock_guard<std::mutex>(data_arr_protect);
| ^
In file included from C:/msys64/mingw64/include/c++/12.1.0/mutex:43,
from D:/Scizzors/Dsktp/cpp/how2thread/src/how2thread.hpp:8,
from D:/Scizzors/Dsktp/cpp/how2thread/src/how2thread.cpp:4:
C:/msys64/mingw64/include/c++/12.1.0/bits/std_mutex.h:237:7: note: declared here
237 | lock_guard(const lock_guard&) = delete;
I specify in my header file, that data_arr_protect is std::mutex object
class Scheduler
{
// class for schedule slicers, processors and collecting data
public:
Scheduler(const std::vector<char>& data,
const std::string& mask); // construct and parse data
Request get_request(); // used to get another batch
void write_request(Request&&);
void write_finding(Finding&& find);
using Find_it = decltype(std::declval<std::vector<Finding>&>().cbegin());
Find_it cbegin();
Find_it cend();
const auto& get_slicing_status(){return is_slicing;} //
std::string mask;
#ifndef DEBUG_V
private:
#endif
const size_t slicer_num;
std::queue<Request> data_arr; // consider switching to deQ
std::mutex data_arr_protect;//for mt rw to vec // might be switching to semaphores
std::queue<Actor_processor> proc_instances_q;
std::queue<Actor_slicer> slicer_instances_q;
std::vector<Finding> result_arr;
std::mutex result_protect;//for mt write to vec
protected:
friend class Actor_slicer; // we need access from slicers to mutexes as they're pretty lowlvl
std::vector<std::mutex> char_segments_protect;
std::vector<size_t> finish_line_no;
std::atomic<size_t> is_slicing; // for break cond
};
My cmake file looks next
cmake_minimum_required(VERSION 3.10.0)
project(how2thread
VERSION 0.0.1
DESCRIPTION "simple mt parser app"
LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(THREADS_PREFER_PTHREAD_FLAG ON)
find_package(Threads REQUIRED)
file(GLOB_RECURSE src_files src/*.cpp)
add_library(how2thread_lib src/how2thread.cpp src/how2thread.hpp)
add_executable(how2thread src/main.cpp)
target_link_libraries(how2thread PRIVATE how2thread_lib)
target_link_libraries(how2thread PRIVATE Threads::Threads)
What can cause compiler's misinterpretation and how i must fix it?
I tried different linking options, as building my how2thread.cpp file with main.cpp file, although it didn't help. And I do not get errors about undefined class or something, so, I guess, header file being included by .cpp one
Nothing is being misinterpreted. The issue is the following line: (Which appears only in the error message, not the code you show. Please always provide a minimal reproducible example!)
auto m_lock = std::lock_guard<std::mutex>(data_arr_protect);
This is copy-initialization of m_lock from the initializer expression which before C++17 required the type to be move-constructible, which std::lock_guard is not. Direct-initialization with auto (e.g. auto m_lock(std::lock_guard<std::mutex>(data_arr_protect));) would also not work for the same reason.
To compile this line you need to use C++17 or later, but you are asking cmake to set C++14 with
set(CMAKE_CXX_STANDARD 14)
So change the 14 to 17.
Or if you require compatibility with C++14, you will have to avoid the auto initialization idiom for non-movable types:
std::lock_guard<std::mutex> m_lock(data_arr_protect);
I am puzzled that this very basic code does not compile on windows with msvc 16.8.3 and c++17 (compiles fine with gcc)
#include "json.hpp"
#include <string>
int main() {
nlohmann::json j;
j["mykey"] = std::string("my value");
return 0;
}
It fails immediately with:
no operator "=" matches these operands -- operand types are: nlohmann::basic_json<std::map, std::vector, std::string, bool, int64_t, uint64_t, double, std::allocator, nlohmann::adl_serializer, std::vector<uint8_t, std::allocator<uint8_t>>> = std::stringC/C++(349)
json.hpp(18662,17): message : could be 'nlohmann::basic_json<std::map,std::vector,std::string,bool,int64_t,uint64_t,double,std::allocator,nlohmann::adl_serializer,std::vector<uint8_t,std::allocator<uint8_t>>> &nlohmann::basic_json<std::map,std::vector,std::string,bool,int64_t,uint64_t,double,std::allocator,nlohmann::adl_serializer,std::vector<uint8_t,std::allocator<uint8_t>>>::operator =(nlohmann::basic_json<std::map,std::vector,std::string,bool,int64_t,uint64_t,double,std::allocator,nlohmann::adl_serializer,std::vector<uint8_t,std::allocator<uint8_t>>>) noexcept'
message : while trying to match the argument list '(nlohmann::basic_json<std::map,std::vector,std::string,bool,int64_t,uint64_t,double,std::allocator,nlohmann::adl_serializer,std::vector<uint8_t,std::allocator<uint8_t>>>, std::string)'
My CMakeLists.txt is super simple:
cmake_minimum_required(VERSION 3.5)
project(api LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
add_executable(jsontest main.cpp json.hpp)
As far as I know you need to use json.parse() to create the string object.
j["mykey"] = nlohmann::json.parse("my value");
But it's been a while since I last used the library.
Good day,
here is my code
#include <iostream>
#include <Magick++.h>
using namespace std;
using namespace Magick;
int main(int argc, char **argv) {
InitializeMagick(*argv);
Image image;
try {
image.read(argv[1]);
}
catch( Exception &error_ ) {
cout << "Caught exception: " << error_.what() << endl;
return 1;
}
int x = image.columns();
cout<<"your picture's width is "<< x << "px"<<endl;
return 0;
}
I use KDevelop(which uses CMake as builder),
when I try to compile the app, it throws me an error
main.cpp:25: undefined reference to `Magick::Image::columns() const'
Here's what my CMakeLists.txt contains.
cmake_minimum_required(VERSION 3.5)
project(hello)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
set(SOURCE_FILES main.cpp)
add_executable(hello ${SOURCE_FILES})
add_definitions( -DMAGICKCORE_QUANTUM_DEPTH=16 )
add_definitions( -DMAGICKCORE_HDRI_ENABLE=0 )
find_package(ImageMagick COMPONENTS Magick++)
include_directories(${ImageMagick_INCLUDE_DIRS})
target_link_libraries(hello ${ImageMagick_LIBRARIES})
I figured out that there're often issues with undefined references when CMakeLists isn't written correctly, but I made it according to this About Magick++, how to write the CMakeLists?
where am I wrong? I can add any information needed.
UPD 1.
version of magick++,
8:6.8.9.9-7ubuntu5.7
system info:
Description: Linux Mint 18.1 Serena
UPD 2.
I just removed parenthesis and when tryed to compile with
size_t x = image.columns;
size_t y = image.rows;
KDevelop threw me
main.cpp:25:22: error: cannot convert ‘Magick::Image::columns’ from type ‘size_t (Magick::Image::)() const {aka long unsigned int (Magick::Image::)() const}’ to type ‘size_t {aka long unsigned int}’
even when
auto x = image.columns;
auto y = image.rows;
it throws
main.cpp:25:20: error: cannot convert ‘Magick::Image::columns’ from
type ‘size_t (Magick::Image::)() const {aka long unsigned int
(Magick::Image::)() const}’ to type ‘long unsigned int
(Magick::Image::*)() const’
what's happening?
P.S. hooray, this is my first question on stackoverflow! :-)
If you are able to compile your program without CMake using g++ main.cpp `Magick++-config --cxxflags --cppflags --ldflags --libs` (but for some reason cannot use ${ImageMagick_LIBRARIES} in CMake), then you can make use of Magick++-config in your CMakeLists.txt:
cmake_minimum_required(VERSION 3.5)
project(hello LANGUAGES CXX)
add_executable(hello main.cpp)
target_compile_features(hello PRIVATE cxx_std_11)
find_package(ImageMagick REQUIRED COMPONENTS Magick++)
target_compile_definitions(hello PRIVATE
MAGICKCORE_QUANTUM_DEPTH=16
MAGICKCORE_HDRI_ENABLE=0
)
target_include_directories(hello PRIVATE ${ImageMagick_INCLUDE_DIRS})
execute_process(COMMAND Magick++-config --ldflags
OUTPUT_VARIABLE ImageMagick_LINK_FLAGS
OUTPUT_STRIP_TRAILING_WHITESPACE
)
target_link_libraries(hello PRIVATE ${ImageMagick_LINK_FLAGS})
Here, execute_process allows us to get the result of Magick++-config --ldflags into a variable, which we can pass as flags to the linker through target_link_libraries.
Also, note how I've used target_compile_features rather than setting the global CMAKE_CXX_FLAGS variable, target_compile_definitions rather than add_definitions and target_include_directories rather than include_directories. It's better to use local (target-based) commands rather than modifying global state, both in programming and in CMake, since they can have unforeseen repercussions down the line -- in the context of CMake, those global commands would have affected nested sub-projects.
ForgottenUbrella 's version which I adapted didn't quite work for me, copying a line in from another project fixed it. Note, I'm using c++20 not 11.
I had the following error:
..... undefined reference to symbol 'pthread_create##GLIBC_2.2.5'
and the line that fixed it:
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++2a -pthread")
I am trying to configure CMake to compile for OS X Target.This is IMac with OS X Yosemite v 10.10.2
Clang version:
Apple LLVM version 6.1.0 (clang-602.0.53) (based on LLVM 3.6.0svn)
Target: x86_64-apple-darwin14.1.0
When I compile without putting any compiler flags I am getting one error for this chunk of code in one the sources:
static const char* LogLevelStr[] {
"TRACE " ,
"INFO " ,
"WARNING" ,
"ERROR " ,
"FATAL " ,
};
error: definition of variable with array type needs an
explicit size or an initializer
I am compiling this code on Windows and GCC and it is completely fine so I don't understand why Clang complains here.So I decided,maybe I have to set C++11 support flags because I use this standard in the code a lot.
Setting
set (CMAKE_CXX_STANDARD 11)
or
set(CMAKE_CXX_FLAGS " -std=c++11")
Adds even more weird errors like these:
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/__bit_reference:51:52:
error:
expected ';' at end of declaration list
_LIBCPP_INLINE_VISIBILITY operator bool() const _NOEXCEPT
^ /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/__bit_reference:87:57:
error:
expected ';' at end of declaration swap(__bit_reference<_Cp> __x, __bit_reference<_Cp> __y) _NOEXCEPT
^ >/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolc>hain/usr/bin/../include/c++/v1/__bit_reference:87:58:
error:
C++ requires a type specifier for all declarations >swap(__bit_reference<_Cp> __x, __bit_reference<_Cp> __y) _NOEXCEPT
^ >/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/__config:338:21:
note:
expanded from macro '_NOEXCEPT'
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/__bit_reference:89:10:
error:
expected '(' for function-style cast or type construction
bool __t = __x;
~~~~ ^ /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/__bit_reference:92:2:
error:
expected ';' after top level declarator } ^ /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/__bit_reference:1111:47:
error:
expected ';' at end of declaration list
_LIBCPP_INLINE_VISIBILITY __bit_iterator() _NOEXCEPT
The error block from above the compiler spits at the point it is trying to parse include
Now,I tried also to set:
set(CMAKE_CXX_FLAGS "-std=c++11 -stdlib=libc++")
Same errors.
What do I miss here?
UPDATE:
I don't understand why some people marked this question for closing.Anyway,here is the problem in more details.I tried all those C++11 flags.I also added '=' to that static array.But most of the errors come after that.And it looks like root of those is .At the very first place where gets parsed it goes down into another class called __bit_reference and there at line 51 the compiler complains
on the following line
_LIBCPP_INLINE_VISIBILITY operator bool() const _NOEXCEPT
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/__bit_reference:51:52:
Expected ';' at end of declaration list
Most of the other errors are also in some ways connected to stl containers.
So my question is still valid.How do I get my source code to compile with the latest Clang on OS X including C++11 support.I am trying to do that with Xcode and have the same issues.
Xcode compiler output(some of it):
CompileC
/Users/michaeliv/Library/Developer/Xcode/DerivedData/xxxxxTest-hdkkzwyyppywsjgmoyuphranqtok/Build/Intermediates/xxxxxxTest.build/Debug/xxxxxxTest.build/Objects-normal/x86_64/XXXMath.o
/Users/XXXXXXX/Documents/XXXXX/xxxxxx/src/XXXMath.cpp normal x86_64
c++ com.apple.compilers.llvm.clang.1_0.compiler
cd /Users/xxxxxx/Desktop/xxxxTest
export LANG=en_US.US-ASCII
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang
-x c++ -arch x86_64 -fmessage-length=0 -fdiagnostics-show-note-include-stack -fmacro-backtrace-limit=0 -std=gnu++11 -stdlib=libc++ ....
It's difficult to say for sure since you aren't posting a reproducible problem.
However, the code sample you posted contains a flaw:
static const char* LogLevelStr[] {
"TRACE " ,
"INFO " ,
"WARNING" ,
"ERROR " ,
"FATAL " ,
};
should be changed to
static const char* LogLevelStr[] = {
"TRACE " ,
"INFO " ,
"WARNING" ,
"ERROR " ,
"FATAL " ,
};
I'm not 100% on this as regards the C++11 standard, however, this is my understanding.
When you write static const char* foo[] = { "foo", "bar", "baz", }; this is aggregate initialization and not list initialization or any other kind. In your code sample, it looks like you are trying to initialize an array using C++11 list-initialization. However, to my knowledge this is not possible, and the "brace-or-equal" syntax described in chapter 8 of the standard does not apply.
This answer refers to "clause 8" to argue that list-initialization of C-style arrays is not permitted by the standard: Initializing a member array in constructor initializer
IMO that is the problem and if I were you I would use an = there, even if it would be allowed to omit it in C++11 or some future standard.
I am trying to compile the following thread pool program posted on code review to test it.
https://codereview.stackexchange.com/questions/55100/platform-independant-thread-pool-v4
But I am getting the errors
threadpool.hpp: In member function ‘std::future<decltype (task((forward<Args>)(args)...))> threadpool::enqueue_task(Func&&, Args&& ...)’:
threadpool.hpp:94:28: error: ‘make_unique’ was not declared in this scope
auto package_ptr = make_unique<task_package_impl<R, decltype(bound_task)>> (std::move(bound_task), std::move(promise));
^
threadpool.hpp:94:81: error: expected primary-expression before ‘>’ token
auto package_ptr = make_unique<task_package_impl<R, decltype(bound_task)>>(std::move(bound_task), std::move(promise));
^
main.cpp: In function ‘int main()’:
main.cpp:9:17: error: ‘make_unique’ is not a member of ‘std’
auto ptr1 = std::make_unique<unsigned>();
^
main.cpp:9:34: error: expected primary-expression before ‘unsigned’
auto ptr1 = std::make_unique<unsigned>();
^
main.cpp:14:17: error: ‘make_unique’ is not a member of ‘std’
auto ptr2 = std::make_unique<unsigned>();
^
main.cpp:14:34: error: expected primary-expression before ‘unsigned’
auto ptr2 = std::make_unique<unsigned>();
make_unique is an upcoming C++14 feature and thus might not be available on your compiler, even if it is C++11 compliant.
You can however easily roll your own implementation:
template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args) {
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
(FYI, here is the final version of make_unique that was voted into C++14. This includes additional functions to cover arrays, but the general idea is still the same.)
If you have latest compiler, you can change the following in your build settings:
C++ Language Dialect C++14[-std=c++14]
This works for me.
1.gcc version >= 5
2.CXXFLAGS += -std=c++14
3. #include <memory>
This happens to me while working with XCode (I'm using the most current version of XCode in 2019...). I'm using, CMake for build integration. Using the following directive in CMakeLists.txt fixed it for me:
set(CMAKE_CXX_STANDARD 14).
Example:
cmake_minimum_required(VERSION 3.14.0)
set(CMAKE_CXX_STANDARD 14)
# Rest of your declarations...
In my case I was needed update the std=c++
I mean in my gradle file was this
android {
...
defaultConfig {
...
externalNativeBuild {
cmake {
cppFlags "-std=c++11", "-Wall"
arguments "-DANDROID_STL=c++_static",
"-DARCORE_LIBPATH=${arcore_libpath}/jni",
"-DARCORE_INCLUDE=${project.rootDir}/app/src/main/libs"
}
}
....
}
I changed this line
android {
...
defaultConfig {
...
externalNativeBuild {
cmake {
cppFlags "-std=c++17", "-Wall" <-- this number from 11 to 17 (or 14)
arguments "-DANDROID_STL=c++_static",
"-DARCORE_LIBPATH=${arcore_libpath}/jni",
"-DARCORE_INCLUDE=${project.rootDir}/app/src/main/libs"
}
}
....
}
That's it...
If you are stuck with c++11, you can get make_unique from abseil-cpp, an open source collection of C++ libraries drawn from Google’s internal codebase.