问:
‘CUDNN_STATUS_VERSION_MISMATCH’ error while installing caffe
I tried the caffe installation with the instruction of http://caffe.berkeleyvision.org/installation.html , the ubuntu installation command sudo apt install caffe-cudadoesn't work at all with the error

```<code>Package caffe-cuda is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

E: Package 'caffe-cuda' has no installation candidate
</code>```

So I follow the 'Compilation with Make' section.

I solved all the dependency issue but finally failed with  ‘CUDNN_STATUS_VERSION_MISMATCH’ error, to troubleshoot the error I googled alot also tried https://anidh.medium.com/install-caffe-on-ubuntu-with-cuda-6d0da9e8f860 and https://qengineering.eu/install-caffe-on-ubuntu-20.04-with-opencv-4.4.html, all failed so I'm asking for help here.

My environment

OS            :Ubuntu 20.04 LTS

GPU           :Nvidia GeForce GTX 1080Ti

Driver version:460.56

CUDA Version  :11.2

cuDNN Version :8.1.1

Python Version:3.8.5

conda version :4.9.2

C compiler    :GNU 9.3.0

Error message(just make):

```<code>(base) a@ai:~/Software/caffe$ make clean
(base) a@ai:~/Software/caffe$ make all -j8
PROTOC src/caffe/proto/caffe.proto
NVCC src/caffe/util/im2col.cu
NVCC src/caffe/util/math_functions.cu
NVCC src/caffe/solvers/adam_solver.cu
NVCC src/caffe/solvers/adagrad_solver.cu
NVCC src/caffe/solvers/adadelta_solver.cu
NVCC src/caffe/solvers/nesterov_solver.cu
NVCC src/caffe/solvers/rmsprop_solver.cu
NVCC src/caffe/solvers/sgd_solver.cu
In file included from src/caffe/util/math_functions.cu:1:
/usr/local/cuda/include/math_functions.h:54:2: warning: #warning "math_functions.h is an internal header file and must not be used directly.  This file will be removed in a future CUDA release.  Please use cuda_runtime_api.h or cuda_runtime.h instead." [-Wcpp]
   54 | #warning "math_functions.h is an internal header file and must not be used directly.  This file will be removed in a future CUDA release.  Please use cuda_runtime_api.h or cuda_runtime.h instead."
      |  ^~~~~~~
NVCC src/caffe/layers/absval_layer.cu
NVCC src/caffe/layers/pooling_layer.cu
     .
     .
     all success
     .
     .
     .
CXX tools/caffe.cpp
CXX tools/compute_image_mean.cpp
In file included from ./include/caffe/util/device_alternate.hpp:40,
                 from ./include/caffe/common.hpp:19,
                 from ./include/caffe/util/db.hpp:6,
                 from tools/compute_image_mean.cpp:12:
./include/caffe/util/cudnn.hpp: In function ‘const char* cudnnGetErrorString(cudnnStatus_t)’:
./include/caffe/util/cudnn.hpp:21:10: warning: enumeration value ‘CUDNN_STATUS_VERSION_MISMATCH’ not handled in switch [-Wswitch]
   21 |   switch (status) {
     .
     .
     all failed with same error
     .
     .
     .
CXX src/caffe/data_transformer.cpp
In file included from ./include/caffe/util/device_alternate.hpp:40,
                 from ./include/caffe/common.hpp:19,
                 from src/caffe/util/io.cpp:18:
./include/caffe/util/cudnn.hpp: In function ‘const char* cudnnGetErrorString(cudnnStatus_t)’:
./include/caffe/util/cudnn.hpp:21:10: warning: enumeration value ‘CUDNN_STATUS_VERSION_MISMATCH’ not handled in switch [-Wswitch]
   21 |   switch (status) {
      |          ^
src/caffe/util/io.cpp: In function ‘cv::Mat caffe::ReadImageToCVMat(const string&, int, int, bool)’:
src/caffe/util/io.cpp:76:34: error: ‘CV_LOAD_IMAGE_COLOR’ was not declared in this scope
   76 |   int cv_read_flag = (is_color ? CV_LOAD_IMAGE_COLOR :
      |                                  ^~~~~~~~~~~~~~~~~~~
src/caffe/util/io.cpp:77:5: error: ‘CV_LOAD_IMAGE_GRAYSCALE’ was not declared in this scope
   77 |     CV_LOAD_IMAGE_GRAYSCALE);
      |     ^~~~~~~~~~~~~~~~~~~~~~~
src/caffe/util/io.cpp: In function ‘cv::Mat caffe::DecodeDatumToCVMat(const caffe::Datum&, bool)’:
src/caffe/util/io.cpp:182:34: error: ‘CV_LOAD_IMAGE_COLOR’ was not declared in this scope
  182 |   int cv_read_flag = (is_color ? CV_LOAD_IMAGE_COLOR :
      |                                  ^~~~~~~~~~~~~~~~~~~
src/caffe/util/io.cpp:183:5: error: ‘CV_LOAD_IMAGE_GRAYSCALE’ was not declared in this scope
  183 |     CV_LOAD_IMAGE_GRAYSCALE);
      |     ^~~~~~~~~~~~~~~~~~~~~~~
make: *** [Makefile:592: .build_release/src/caffe/util/io.o] Error 1
make: *** Waiting for unfinished jobs....
In file included from ./include/caffe/util/device_alternate.hpp:40,
                 from ./include/caffe/common.hpp:19,
                 from ./include/caffe/util/db.hpp:6,
                 from ./include/caffe/util/db_lmdb.hpp:10,
                 from src/caffe/util/db_lmdb.cpp:2:
./include/caffe/util/cudnn.hpp: In function ‘const char* cudnnGetErrorString(cudnnStatus_t)’:
./include/caffe/util/cudnn.hpp:21:10: warning: enumeration value ‘CUDNN_STATUS_VERSION_MISMATCH’ not handled in switch [-Wswitch]
   21 |   switch (status) {
      |          ^
     .
     .
     all failed with same error
     .
     .
     .
In file included from ./include/caffe/util/device_alternate.hpp:40,
                 from ./include/caffe/common.hpp:19,
                 from ./include/caffe/blob.hpp:8,
                 from ./include/caffe/data_transformer.hpp:6,
                 from src/caffe/data_transformer.cpp:8:
./include/caffe/util/cudnn.hpp: In function ‘const char* cudnnGetErrorString(cudnnStatus_t)’:
./include/caffe/util/cudnn.hpp:21:10: warning: enumeration value ‘CUDNN_STATUS_VERSION_MISMATCH’ not handled in switch [-Wswitch]
   21 |   switch (status) {
      |          ^
</code>```

Another error message(cmake then make):

```<code>(base) a@ai:~/Software/caffe$ mkdir build
(base) a@ai:~/Software/caffe$ cd build/
(base) a@ai:~/Software/caffe/build$ cmake ..
-- The C compiler identification is GNU 9.3.0
-- The CXX compiler identification is GNU 9.3.0
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
CMake Warning (dev) at cmake/Misc.cmake:32 (set):
  implicitly converting 'BOOLEAN' to 'STRING' type.
Call Stack (most recent call first):
  CMakeLists.txt:25 (include)
This warning is for project developers.  Use -Wno-dev to suppress it.

-- Found Boost: /usr/lib/x86_64-linux-gnu/cmake/Boost-1.71.0/BoostConfig.cmake (found suitable version "1.71.0", minimum required is "1.54") found components: system thread filesystem
-- Found Threads: TRUE
-- Found GFlags: /usr/include
-- Found gflags  (include: /usr/include, library: /usr/lib/x86_64-linux-gnu/libgflags.so)
-- Found Glog: /usr/include
-- Found glog    (include: /usr/include, library: /usr/lib/x86_64-linux-gnu/libglog.so)
-- Found Protobuf: /usr/lib/x86_64-linux-gnu/libprotobuf.so;-lpthread (found version "3.6.1")
-- Found PROTOBUF Compiler: /usr/bin/protoc
-- HDF5: Using hdf5 compiler wrapper to determine C configuration
-- HDF5: Using hdf5 compiler wrapper to determine CXX configuration
-- Found HDF5: /usr/lib/x86_64-linux-gnu/hdf5/serial/libhdf5_cpp.so;/usr/lib/x86_64-linux-gnu/hdf5/serial/libhdf5.so;/usr/lib/x86_64-linux-gnu/libpthread.so;/usr/lib/x86_64-linux-gnu/libsz.so;/usr/lib/x86_64-linux-gnu/libz.so;/usr/lib/x86_64-linux-gnu/libdl.so;/usr/lib/x86_64-linux-gnu/libm.so (found version "1.10.4") found components: HL
-- Found LMDB: /usr/include
-- Found lmdb    (include: /usr/include, library: /usr/lib/x86_64-linux-gnu/liblmdb.so)
-- Found LevelDB: /usr/include
-- Found LevelDB (include: /usr/include, library: /usr/lib/x86_64-linux-gnu/libleveldb.so)
-- Found Snappy: /usr/include
-- Found Snappy  (include: /usr/include, library: /usr/lib/x86_64-linux-gnu/libsnappy.so)
-- CUDA detected: 11.2
-- Found cuDNN: ver. 8.1.1 found (include: /usr/include, library: /usr/lib/x86_64-linux-gnu/libcudnn.so)
-- Added CUDA NVCC flags for: sm_61
-- OpenCV found (/usr/lib/x86_64-linux-gnu/cmake/opencv4)
-- Found Atlas: /usr/include/x86_64-linux-gnu
-- Found Atlas (include: /usr/include/x86_64-linux-gnu library: /usr/lib/x86_64-linux-gnu/libatlas.so lapack: /usr/lib/x86_64-linux-gnu/liblapack.so
-- Found PythonInterp: /usr/bin/python2.7 (found suitable version "2.7.18", minimum required is "2.7")
-- Found PythonLibs: /usr/lib/x86_64-linux-gnu/libpython2.7.so (found suitable version "2.7.18", minimum required is "2.7")
-- Found NumPy: /usr/lib/python2.7/dist-packages/numpy/core/include (found suitable version "1.16.5", minimum required is "1.7.1")
-- NumPy ver. 1.16.5 found (include: /usr/lib/python2.7/dist-packages/numpy/core/include)
-- Found Boost: /usr/lib/x86_64-linux-gnu/cmake/Boost-1.71.0/BoostConfig.cmake (found suitable version "1.71.0", minimum required is "1.46") found components: python
-- Found Doxygen: /usr/bin/doxygen (found version "1.8.17") found components: doxygen missing components: dot
-- Detected Doxygen OUTPUT_DIRECTORY: ./doxygen/
-- Found Git: /usr/bin/git (found version "2.25.1")
--
-- ******************* Caffe Configuration Summary *******************
-- General:
--   Version           :   1.0.0
--   Git               :   unknown
--   System            :   Linux
--   C++ compiler      :   /usr/bin/c++
--   Release CXX flags :   -O3 -DNDEBUG -fPIC -Wall -Wno-sign-compare -Wno-uninitialized
--   Debug CXX flags   :   -g -fPIC -Wall -Wno-sign-compare -Wno-uninitialized
--   Build type        :   Release
--
--   BUILD_SHARED_LIBS :   ON
--   BUILD_python      :   ON
--   BUILD_matlab      :   OFF
--   BUILD_docs        :   ON
--   CPU_ONLY          :   OFF
--   USE_OPENCV        :   ON
--   USE_LEVELDB       :   ON
--   USE_LMDB          :   ON
--   USE_NCCL          :   OFF
--   ALLOW_LMDB_NOLOCK :   OFF
--   USE_HDF5          :   ON
--
-- Dependencies:
--   BLAS              :   Yes (Atlas)
--   Boost             :   Yes (ver. 1.71)
--   glog              :   Yes
--   gflags            :   Yes
--   protobuf          :   Yes (ver. 3.6.1)
--   lmdb              :   Yes (ver. 0.9.24)
--   LevelDB           :   Yes (ver. 1.22)
--   Snappy            :   Yes (ver. 1.1.8)
--   OpenCV            :   Yes (ver. 4.2.0)
--   CUDA              :   Yes (ver. 11.2)
--
-- NVIDIA CUDA:
--   Target GPU(s)     :   Auto
--   GPU arch(s)       :   sm_61
--   cuDNN             :   Yes (ver. 8.1.1)
--
-- Python:
--   Interpreter       :   /usr/bin/python2.7 (ver. 2.7.18)
--   Libraries         :   /usr/lib/x86_64-linux-gnu/libpython2.7.so (ver 2.7.18)
--   NumPy             :   /usr/lib/python2.7/dist-packages/numpy/core/include (ver 1.16.5)
--
-- Documentaion:
--   Doxygen           :   /usr/bin/doxygen (1.8.17)
--   config_file       :   /home/a/Software/caffe/.Doxyfile
--
-- Install:
--   Install path      :   /home/a/Software/caffe/build/install
--
-- Configuring done
CMake Warning at src/caffe/CMakeLists.txt:23 (add_library):
  Cannot generate a safe runtime search path for target caffe because files
  in some directories may conflict with libraries in implicit directories:

    runtime library [libcudnn.so.8] in /usr/lib/x86_64-linux-gnu may be hidden by files in:
      /usr/local/cuda-11.2/lib64

  Some of these libraries may not be found correctly.

CMake Warning at python/CMakeLists.txt:8 (add_library):
  Cannot generate a safe runtime search path for target pycaffe because files
  in some directories may conflict with libraries in implicit directories:

    runtime library [libcudnn.so.8] in /usr/lib/x86_64-linux-gnu may be hidden by files in:
      /usr/local/cuda-11.2/lib64

  Some of these libraries may not be found correctly.

-- Generating done
-- Build files have been written to: /home/a/Software/caffe/build
(base) a@ai:~/Software/caffe/build$ make all
[  1%] Running C++/Python protocol buffer compiler on /home/a/Software/caffe/src/caffe/proto/caffe.proto
Scanning dependencies of target caffeproto
[  1%] Building CXX object src/caffe/CMakeFiles/caffeproto.dir/__/__/include/caffe/proto/caffe.pb.cc.o
[  1%] Linking CXX static library ../../lib/libcaffeproto.a
[  1%] Built target caffeproto
[  1%] Building NVCC (Device) object src/caffe/CMakeFiles/cuda_compile_1.dir/util/cuda_compile_1_generated_math_functions.cu.o
In file included from /home/a/Software/caffe/src/caffe/util/math_functions.cu:1:
/usr/local/cuda-11.2/include/math_functions.h:54:2: warning: #warning "math_functions.h is an internal header file and must not be used directly.  This file will be removed in a future CUDA release.  Please use cuda_runtime_api.h or cuda_runtime.h instead." [-Wcpp]
/home/a/Software/caffe/include/caffe/util/cudnn.hpp: In function ‘const char* cudnnGetErrorString(cudnnStatus_t)’:
/home/a/Software/caffe/include/caffe/util/cudnn.hpp:21:8: warning: enumeration value ‘CUDNN_STATUS_VERSION_MISMATCH’ not handled in switch [-Wswitch]
   21 |   switch (status) {
      |        ^
[  1%] Building NVCC (Device) object src/caffe/CMakeFiles/cuda_compile_1.dir/layers/cuda_compile_1_generated_absval_layer.cu.o
/home/a/Software/caffe/include/caffe/util/cudnn.hpp: In function ‘const char* cudnnGetErrorString(cudnnStatus_t)’:
/home/a/Software/caffe/include/caffe/util/cudnn.hpp:21:8: warning: enumeration value ‘CUDNN_STATUS_VERSION_MISMATCH’ not handled in switch [-Wswitch]

            .
     .
     dozens of same error
     .
     .
     .
   21 |   switch (status) {
      |          ^
/home/a/Software/caffe/src/caffe/layers/cudnn_conv_layer.cpp: In member function ‘virtual void caffe::CuDNNConvolutionLayer<Dtype>::Reshape(const std::vector<caffe::Blob<Dtype>*>&, const std::vector<caffe::Blob<Dtype>*>&)’:
/home/a/Software/caffe/src/caffe/layers/cudnn_conv_layer.cpp:136:7: error: ‘CUDNN_CONVOLUTION_FWD_SPECIFY_WORKSPACE_LIMIT’ was not declared in this scope
  136 |       CUDNN_CONVOLUTION_FWD_SPECIFY_WORKSPACE_LIMIT,
      |       ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/a/Software/caffe/include/caffe/util/cudnn.hpp:15:28: note: in definition of macro ‘CUDNN_CHECK’
   15 |     cudnnStatus_t status = condition; \
      |                            ^~~~~~~~~
/home/a/Software/caffe/src/caffe/layers/cudnn_conv_layer.cpp:131:17: error: there are no arguments to ‘cudnnGetConvolutionForwardAlgorithm’ that depend on a template parameter, so a declaration of ‘cudnnGetConvolutionForwardAlgorithm’ must be available [-fpermissive]
  131 |     CUDNN_CHECK(cudnnGetConvolutionForwardAlgorithm(handle_[0],
      |                 ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/a/Software/caffe/include/caffe/util/cudnn.hpp:15:28: note: in definition of macro ‘CUDNN_CHECK’
   15 |     cudnnStatus_t status = condition; \
      |                            ^~~~~~~~~
/home/a/Software/caffe/src/caffe/layers/cudnn_conv_layer.cpp:131:17: note: (if you use ‘-fpermissive’, G++ will accept your code, but allowing the use of an undeclared name is deprecated)
  131 |     CUDNN_CHECK(cudnnGetConvolutionForwardAlgorithm(handle_[0],
      |                 ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/a/Software/caffe/include/caffe/util/cudnn.hpp:15:28: note: in definition of macro ‘CUDNN_CHECK’
   15 |     cudnnStatus_t status = condition; \
      |                            ^~~~~~~~~
/home/a/Software/caffe/src/caffe/layers/cudnn_conv_layer.cpp:151:11: error: ‘CUDNN_CONVOLUTION_BWD_FILTER_SPECIFY_WORKSPACE_LIMIT’ was not declared in this scope
  151 |           CUDNN_CONVOLUTION_BWD_FILTER_SPECIFY_WORKSPACE_LIMIT,
      |           ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/a/Software/caffe/include/caffe/util/cudnn.hpp:15:28: note: in definition of macro ‘CUDNN_CHECK’
   15 |     cudnnStatus_t status = condition; \
      |                            ^~~~~~~~~
/home/a/Software/caffe/src/caffe/layers/cudnn_conv_layer.cpp:149:17: error: there are no arguments to ‘cudnnGetConvolutionBackwardFilterAlgorithm’ that depend on a template parameter, so a declaration of ‘cudnnGetConvolutionBackwardFilterAlgorithm’ must be available [-fpermissive]
  149 |     CUDNN_CHECK(cudnnGetConvolutionBackwardFilterAlgorithm(handle_[0],
      |                 ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/a/Software/caffe/include/caffe/util/cudnn.hpp:15:28: note: in definition of macro ‘CUDNN_CHECK’
   15 |     cudnnStatus_t status = condition; \
      |                            ^~~~~~~~~
/home/a/Software/caffe/src/caffe/layers/cudnn_conv_layer.cpp:162:11: error: ‘CUDNN_CONVOLUTION_BWD_DATA_SPECIFY_WORKSPACE_LIMIT’ was not declared in this scope
  162 |           CUDNN_CONVOLUTION_BWD_DATA_SPECIFY_WORKSPACE_LIMIT,
      |           ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/a/Software/caffe/include/caffe/util/cudnn.hpp:15:28: note: in definition of macro ‘CUDNN_CHECK’
   15 |     cudnnStatus_t status = condition; \
      |                            ^~~~~~~~~
/home/a/Software/caffe/src/caffe/layers/cudnn_conv_layer.cpp:160:17: error: there are no arguments to ‘cudnnGetConvolutionBackwardDataAlgorithm’ that depend on a template parameter, so a declaration of ‘cudnnGetConvolutionBackwardDataAlgorithm’ must be available [-fpermissive]
  160 |     CUDNN_CHECK(cudnnGetConvolutionBackwardDataAlgorithm(handle_[0],
      |                 ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/a/Software/caffe/include/caffe/util/cudnn.hpp:15:28: note: in definition of macro ‘CUDNN_CHECK’
   15 |     cudnnStatus_t status = condition; \
      |                            ^~~~~~~~~
/home/a/Software/caffe/src/caffe/layers/cudnn_conv_layer.cpp: In instantiation of ‘void caffe::CuDNNConvolutionLayer<Dtype>::Reshape(const std::vector<caffe::Blob<Dtype>*>&, const std::vector<caffe::Blob<Dtype>*>&) [with Dtype = float]’:
/home/a/Software/caffe/src/caffe/layers/cudnn_conv_layer.cpp:266:1:   required from here
/home/a/Software/caffe/src/caffe/layers/cudnn_conv_layer.cpp:131:52: error: ‘cudnnGetConvolutionForwardAlgorithm’ was not declared in this scope; did you mean ‘cudnnGetConvolutionForwardAlgorithm_v7’?
  131 |     CUDNN_CHECK(cudnnGetConvolutionForwardAlgorithm(handle_[0],
      |                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~
  132 |       bottom_descs_[i],
      |       ~~~~~~~~~~~~~~~~~
  133 |       filter_desc_,
      |       ~~~~~~~~~~~~~
  134 |       conv_descs_[i],
      |       ~~~~~~~~~~~~~~~
  135 |       top_descs_[i],
      |       ~~~~~~~~~~~~~~
  136 |       CUDNN_CONVOLUTION_FWD_SPECIFY_WORKSPACE_LIMIT,
      |       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  137 |       workspace_limit_bytes,
      |       ~~~~~~~~~~~~~~~~~~~~~~
  138 |       &fwd_algo_[i]));
      |       ~~~~~~~~~~~~~~
/home/a/Software/caffe/include/caffe/util/cudnn.hpp:15:28: note: in definition of macro ‘CUDNN_CHECK’
   15 |     cudnnStatus_t status = condition; \
      |                            ^~~~~~~~~
/home/a/Software/caffe/src/caffe/layers/cudnn_conv_layer.cpp:149:59: error: ‘cudnnGetConvolutionBackwardFilterAlgorithm’ was not declared in this scope; did you mean ‘cudnnGetConvolutionBackwardFilterAlgorithm_v7’?
  149 |     CUDNN_CHECK(cudnnGetConvolutionBackwardFilterAlgorithm(handle_[0],
      |                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~
  150 |           bottom_descs_[i], top_descs_[i], conv_descs_[i], filter_desc_,
      |           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  151 |           CUDNN_CONVOLUTION_BWD_FILTER_SPECIFY_WORKSPACE_LIMIT,
      |           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  152 |           workspace_limit_bytes, &bwd_filter_algo_[i]) );
      |           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/a/Software/caffe/include/caffe/util/cudnn.hpp:15:28: note: in definition of macro ‘CUDNN_CHECK’
   15 |     cudnnStatus_t status = condition; \
      |                            ^~~~~~~~~
/home/a/Software/caffe/src/caffe/layers/cudnn_conv_layer.cpp:160:57: error: ‘cudnnGetConvolutionBackwardDataAlgorithm’ was not declared in this scope; did you mean ‘cudnnGetConvolutionBackwardDataAlgorithm_v7’?
  160 |     CUDNN_CHECK(cudnnGetConvolutionBackwardDataAlgorithm(handle_[0],
      |                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~
  161 |           filter_desc_, top_descs_[i], conv_descs_[i], bottom_descs_[i],
      |           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  162 |           CUDNN_CONVOLUTION_BWD_DATA_SPECIFY_WORKSPACE_LIMIT,
      |           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  163 |         workspace_limit_bytes, &bwd_data_algo_[i]));
      |         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/a/Software/caffe/include/caffe/util/cudnn.hpp:15:28: note: in definition of macro ‘CUDNN_CHECK’
   15 |     cudnnStatus_t status = condition; \
      |                            ^~~~~~~~~
/home/a/Software/caffe/src/caffe/layers/cudnn_conv_layer.cpp: In instantiation of ‘void caffe::CuDNNConvolutionLayer<Dtype>::Reshape(const std::vector<caffe::Blob<Dtype>*>&, const std::vector<caffe::Blob<Dtype>*>&) [with Dtype = double]’:
/home/a/Software/caffe/src/caffe/layers/cudnn_conv_layer.cpp:266:1:   required from here
/home/a/Software/caffe/src/caffe/layers/cudnn_conv_layer.cpp:131:52: error: ‘cudnnGetConvolutionForwardAlgorithm’ was not declared in this scope; did you mean ‘cudnnGetConvolutionForwardAlgorithm_v7’?
  131 |     CUDNN_CHECK(cudnnGetConvolutionForwardAlgorithm(handle_[0],
      |                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~
  132 |       bottom_descs_[i],
      |       ~~~~~~~~~~~~~~~~~
  133 |       filter_desc_,
      |       ~~~~~~~~~~~~~
  134 |       conv_descs_[i],
      |       ~~~~~~~~~~~~~~~
  135 |       top_descs_[i],
      |       ~~~~~~~~~~~~~~
  136 |       CUDNN_CONVOLUTION_FWD_SPECIFY_WORKSPACE_LIMIT,
      |       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  137 |       workspace_limit_bytes,
      |       ~~~~~~~~~~~~~~~~~~~~~~
  138 |       &fwd_algo_[i]));
      |       ~~~~~~~~~~~~~~
/home/a/Software/caffe/include/caffe/util/cudnn.hpp:15:28: note: in definition of macro ‘CUDNN_CHECK’
   15 |     cudnnStatus_t status = condition; \
      |                            ^~~~~~~~~
/home/a/Software/caffe/src/caffe/layers/cudnn_conv_layer.cpp:149:59: error: ‘cudnnGetConvolutionBackwardFilterAlgorithm’ was not declared in this scope; did you mean ‘cudnnGetConvolutionBackwardFilterAlgorithm_v7’?
  149 |     CUDNN_CHECK(cudnnGetConvolutionBackwardFilterAlgorithm(handle_[0],
      |                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~
  150 |           bottom_descs_[i], top_descs_[i], conv_descs_[i], filter_desc_,
      |           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  151 |           CUDNN_CONVOLUTION_BWD_FILTER_SPECIFY_WORKSPACE_LIMIT,
      |           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  152 |           workspace_limit_bytes, &bwd_filter_algo_[i]) );
      |           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/a/Software/caffe/include/caffe/util/cudnn.hpp:15:28: note: in definition of macro ‘CUDNN_CHECK’
   15 |     cudnnStatus_t status = condition; \
      |                            ^~~~~~~~~
/home/a/Software/caffe/src/caffe/layers/cudnn_conv_layer.cpp:160:57: error: ‘cudnnGetConvolutionBackwardDataAlgorithm’ was not declared in this scope; did you mean ‘cudnnGetConvolutionBackwardDataAlgorithm_v7’?
  160 |     CUDNN_CHECK(cudnnGetConvolutionBackwardDataAlgorithm(handle_[0],
      |                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~
  161 |           filter_desc_, top_descs_[i], conv_descs_[i], bottom_descs_[i],
      |           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  162 |           CUDNN_CONVOLUTION_BWD_DATA_SPECIFY_WORKSPACE_LIMIT,
      |           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  163 |         workspace_limit_bytes, &bwd_data_algo_[i]));
      |         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/a/Software/caffe/include/caffe/util/cudnn.hpp:15:28: note: in definition of macro ‘CUDNN_CHECK’
   15 |     cudnnStatus_t status = condition; \
      |                            ^~~~~~~~~
make[2]: *** [src/caffe/CMakeFiles/caffe.dir/build.make:764: src/caffe/CMakeFiles/caffe.dir/layers/cudnn_conv_layer.cpp.o] Error 1
make[1]: *** [CMakeFiles/Makefile2:401: src/caffe/CMakeFiles/caffe.dir/all] Error 2
make: *** [Makefile:130: all] Error 2
(base) a@ai:~/Software/caffe/build$ cd ..
</code>```

答: I followed the directions here and was able to install openpose on top of caffe. In particular, I downgraded g++ to 3.8. I also installed cuda-toolkit-11-3 Ubuntu package.

Body:
I tried the caffe installation with the instruction of http://caffe.berkeleyvision.org/installation.html , the ubuntu installation command sudo apt install caffe-cudadoesn't work at all with the error

Package caffe-cuda is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

E: Package 'caffe-cuda' has no installation candidate

So I follow the 'Compilation with Make' section.

I solved all the dependency issue but finally failed with  ‘CUDNN_STATUS_VERSION_MISMATCH’ error, to troubleshoot the error I googled alot also tried https://anidh.medium.com/install-caffe-on-ubuntu-with-cuda-6d0da9e8f860 and https://qengineering.eu/install-caffe-on-ubuntu-20.04-with-opencv-4.4.html, all failed so I'm asking for help here.

My environment

OS            :Ubuntu 20.04 LTS

GPU           :Nvidia GeForce GTX 1080Ti

Driver version:460.56

CUDA Version  :11.2

cuDNN Version :8.1.1

Python Version:3.8.5

conda version :4.9.2

C compiler    :GNU 9.3.0

Error message(just make):

(base) a@ai:~/Software/caffe$ make clean
(base) a@ai:~/Software/caffe$ make all -j8
PROTOC src/caffe/proto/caffe.proto
NVCC src/caffe/util/im2col.cu
NVCC src/caffe/util/math_functions.cu
NVCC src/caffe/solvers/adam_solver.cu
NVCC src/caffe/solvers/adagrad_solver.cu
NVCC src/caffe/solvers/adadelta_solver.cu
NVCC src/caffe/solvers/nesterov_solver.cu
NVCC src/caffe/solvers/rmsprop_solver.cu
NVCC src/caffe/solvers/sgd_solver.cu
In file included from src/caffe/util/math_functions.cu:1:
/usr/local/cuda/include/math_functions.h:54:2: warning: #warning "math_functions.h is an internal header file and must not be used directly.  This file will be removed in a future CUDA release.  Please use cuda_runtime_api.h or cuda_runtime.h instead." [-Wcpp]
   54 | #warning "math_functions.h is an internal header file and must not be used directly.  This file will be removed in a future CUDA release.  Please use cuda_runtime_api.h or cuda_runtime.h instead."
      |  ^~~~~~~
NVCC src/caffe/layers/absval_layer.cu
NVCC src/caffe/layers/pooling_layer.cu
     .
     .
     all success
     .
     .
     .
CXX tools/caffe.cpp
CXX tools/compute_image_mean.cpp
In file included from ./include/caffe/util/device_alternate.hpp:40,
                 from ./include/caffe/common.hpp:19,
                 from ./include/caffe/util/db.hpp:6,
                 from tools/compute_image_mean.cpp:12:
./include/caffe/util/cudnn.hpp: In function ‘const char* cudnnGetErrorString(cudnnStatus_t)’:
./include/caffe/util/cudnn.hpp:21:10: warning: enumeration value ‘CUDNN_STATUS_VERSION_MISMATCH’ not handled in switch [-Wswitch]
   21 |   switch (status) {
     .
     .
     all failed with same error
     .
     .
     .
CXX src/caffe/data_transformer.cpp
In file included from ./include/caffe/util/device_alternate.hpp:40,
                 from ./include/caffe/common.hpp:19,
                 from src/caffe/util/io.cpp:18:
./include/caffe/util/cudnn.hpp: In function ‘const char* cudnnGetErrorString(cudnnStatus_t)’:
./include/caffe/util/cudnn.hpp:21:10: warning: enumeration value ‘CUDNN_STATUS_VERSION_MISMATCH’ not handled in switch [-Wswitch]
   21 |   switch (status) {
      |          ^
src/caffe/util/io.cpp: In function ‘cv::Mat caffe::ReadImageToCVMat(const string&, int, int, bool)’:
src/caffe/util/io.cpp:76:34: error: ‘CV_LOAD_IMAGE_COLOR’ was not declared in this scope
   76 |   int cv_read_flag = (is_color ? CV_LOAD_IMAGE_COLOR :
      |                                  ^~~~~~~~~~~~~~~~~~~
src/caffe/util/io.cpp:77:5: error: ‘CV_LOAD_IMAGE_GRAYSCALE’ was not declared in this scope
   77 |     CV_LOAD_IMAGE_GRAYSCALE);
      |     ^~~~~~~~~~~~~~~~~~~~~~~
src/caffe/util/io.cpp: In function ‘cv::Mat caffe::DecodeDatumToCVMat(const caffe::Datum&, bool)’:
src/caffe/util/io.cpp:182:34: error: ‘CV_LOAD_IMAGE_COLOR’ was not declared in this scope
  182 |   int cv_read_flag = (is_color ? CV_LOAD_IMAGE_COLOR :
      |                                  ^~~~~~~~~~~~~~~~~~~
src/caffe/util/io.cpp:183:5: error: ‘CV_LOAD_IMAGE_GRAYSCALE’ was not declared in this scope
  183 |     CV_LOAD_IMAGE_GRAYSCALE);
      |     ^~~~~~~~~~~~~~~~~~~~~~~
make: *** [Makefile:592: .build_release/src/caffe/util/io.o] Error 1
make: *** Waiting for unfinished jobs....
In file included from ./include/caffe/util/device_alternate.hpp:40,
                 from ./include/caffe/common.hpp:19,
                 from ./include/caffe/util/db.hpp:6,
                 from ./include/caffe/util/db_lmdb.hpp:10,
                 from src/caffe/util/db_lmdb.cpp:2:
./include/caffe/util/cudnn.hpp: In function ‘const char* cudnnGetErrorString(cudnnStatus_t)’:
./include/caffe/util/cudnn.hpp:21:10: warning: enumeration value ‘CUDNN_STATUS_VERSION_MISMATCH’ not handled in switch [-Wswitch]
   21 |   switch (status) {
      |          ^
     .
     .
     all failed with same error
     .
     .
     .
In file included from ./include/caffe/util/device_alternate.hpp:40,
                 from ./include/caffe/common.hpp:19,
                 from ./include/caffe/blob.hpp:8,
                 from ./include/caffe/data_transformer.hpp:6,
                 from src/caffe/data_transformer.cpp:8:
./include/caffe/util/cudnn.hpp: In function ‘const char* cudnnGetErrorString(cudnnStatus_t)’:
./include/caffe/util/cudnn.hpp:21:10: warning: enumeration value ‘CUDNN_STATUS_VERSION_MISMATCH’ not handled in switch [-Wswitch]
   21 |   switch (status) {
      |          ^

Another error message(cmake then make):

(base) a@ai:~/Software/caffe$ mkdir build
(base) a@ai:~/Software/caffe$ cd build/
(base) a@ai:~/Software/caffe/build$ cmake ..
-- The C compiler identification is GNU 9.3.0
-- The CXX compiler identification is GNU 9.3.0
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
CMake Warning (dev) at cmake/Misc.cmake:32 (set):
  implicitly converting 'BOOLEAN' to 'STRING' type.
Call Stack (most recent call first):
  CMakeLists.txt:25 (include)
This warning is for project developers.  Use -Wno-dev to suppress it.

-- Found Boost: /usr/lib/x86_64-linux-gnu/cmake/Boost-1.71.0/BoostConfig.cmake (found suitable version "1.71.0", minimum required is "1.54") found components: system thread filesystem
-- Found Threads: TRUE
-- Found GFlags: /usr/include
-- Found gflags  (include: /usr/include, library: /usr/lib/x86_64-linux-gnu/libgflags.so)
-- Found Glog: /usr/include
-- Found glog    (include: /usr/include, library: /usr/lib/x86_64-linux-gnu/libglog.so)
-- Found Protobuf: /usr/lib/x86_64-linux-gnu/libprotobuf.so;-lpthread (found version "3.6.1")
-- Found PROTOBUF Compiler: /usr/bin/protoc
-- HDF5: Using hdf5 compiler wrapper to determine C configuration
-- HDF5: Using hdf5 compiler wrapper to determine CXX configuration
-- Found HDF5: /usr/lib/x86_64-linux-gnu/hdf5/serial/libhdf5_cpp.so;/usr/lib/x86_64-linux-gnu/hdf5/serial/libhdf5.so;/usr/lib/x86_64-linux-gnu/libpthread.so;/usr/lib/x86_64-linux-gnu/libsz.so;/usr/lib/x86_64-linux-gnu/libz.so;/usr/lib/x86_64-linux-gnu/libdl.so;/usr/lib/x86_64-linux-gnu/libm.so (found version "1.10.4") found components: HL
-- Found LMDB: /usr/include
-- Found lmdb    (include: /usr/include, library: /usr/lib/x86_64-linux-gnu/liblmdb.so)
-- Found LevelDB: /usr/include
-- Found LevelDB (include: /usr/include, library: /usr/lib/x86_64-linux-gnu/libleveldb.so)
-- Found Snappy: /usr/include
-- Found Snappy  (include: /usr/include, library: /usr/lib/x86_64-linux-gnu/libsnappy.so)
-- CUDA detected: 11.2
-- Found cuDNN: ver. 8.1.1 found (include: /usr/include, library: /usr/lib/x86_64-linux-gnu/libcudnn.so)
-- Added CUDA NVCC flags for: sm_61
-- OpenCV found (/usr/lib/x86_64-linux-gnu/cmake/opencv4)
-- Found Atlas: /usr/include/x86_64-linux-gnu
-- Found Atlas (include: /usr/include/x86_64-linux-gnu library: /usr/lib/x86_64-linux-gnu/libatlas.so lapack: /usr/lib/x86_64-linux-gnu/liblapack.so
-- Found PythonInterp: /usr/bin/python2.7 (found suitable version "2.7.18", minimum required is "2.7")
-- Found PythonLibs: /usr/lib/x86_64-linux-gnu/libpython2.7.so (found suitable version "2.7.18", minimum required is "2.7")
-- Found NumPy: /usr/lib/python2.7/dist-packages/numpy/core/include (found suitable version "1.16.5", minimum required is "1.7.1")
-- NumPy ver. 1.16.5 found (include: /usr/lib/python2.7/dist-packages/numpy/core/include)
-- Found Boost: /usr/lib/x86_64-linux-gnu/cmake/Boost-1.71.0/BoostConfig.cmake (found suitable version "1.71.0", minimum required is "1.46") found components: python
-- Found Doxygen: /usr/bin/doxygen (found version "1.8.17") found components: doxygen missing components: dot
-- Detected Doxygen OUTPUT_DIRECTORY: ./doxygen/
-- Found Git: /usr/bin/git (found version "2.25.1")
--
-- ******************* Caffe Configuration Summary *******************
-- General:
--   Version           :   1.0.0
--   Git               :   unknown
--   System            :   Linux
--   C++ compiler      :   /usr/bin/c++
--   Release CXX flags :   -O3 -DNDEBUG -fPIC -Wall -Wno-sign-compare -Wno-uninitialized
--   Debug CXX flags   :   -g -fPIC -Wall -Wno-sign-compare -Wno-uninitialized
--   Build type        :   Release
--
--   BUILD_SHARED_LIBS :   ON
--   BUILD_python      :   ON
--   BUILD_matlab      :   OFF
--   BUILD_docs        :   ON
--   CPU_ONLY          :   OFF
--   USE_OPENCV        :   ON
--   USE_LEVELDB       :   ON
--   USE_LMDB          :   ON
--   USE_NCCL          :   OFF
--   ALLOW_LMDB_NOLOCK :   OFF
--   USE_HDF5          :   ON
--
-- Dependencies:
--   BLAS              :   Yes (Atlas)
--   Boost             :   Yes (ver. 1.71)
--   glog              :   Yes
--   gflags            :   Yes
--   protobuf          :   Yes (ver. 3.6.1)
--   lmdb              :   Yes (ver. 0.9.24)
--   LevelDB           :   Yes (ver. 1.22)
--   Snappy            :   Yes (ver. 1.1.8)
--   OpenCV            :   Yes (ver. 4.2.0)
--   CUDA              :   Yes (ver. 11.2)
--
-- NVIDIA CUDA:
--   Target GPU(s)     :   Auto
--   GPU arch(s)       :   sm_61
--   cuDNN             :   Yes (ver. 8.1.1)
--
-- Python:
--   Interpreter       :   /usr/bin/python2.7 (ver. 2.7.18)
--   Libraries         :   /usr/lib/x86_64-linux-gnu/libpython2.7.so (ver 2.7.18)
--   NumPy             :   /usr/lib/python2.7/dist-packages/numpy/core/include (ver 1.16.5)
--
-- Documentaion:
--   Doxygen           :   /usr/bin/doxygen (1.8.17)
--   config_file       :   /home/a/Software/caffe/.Doxyfile
--
-- Install:
--   Install path      :   /home/a/Software/caffe/build/install
--
-- Configuring done
CMake Warning at src/caffe/CMakeLists.txt:23 (add_library):
  Cannot generate a safe runtime search path for target caffe because files
  in some directories may conflict with libraries in implicit directories:

    runtime library [libcudnn.so.8] in /usr/lib/x86_64-linux-gnu may be hidden by files in:
      /usr/local/cuda-11.2/lib64

  Some of these libraries may not be found correctly.

CMake Warning at python/CMakeLists.txt:8 (add_library):
  Cannot generate a safe runtime search path for target pycaffe because files
  in some directories may conflict with libraries in implicit directories:

    runtime library [libcudnn.so.8] in /usr/lib/x86_64-linux-gnu may be hidden by files in:
      /usr/local/cuda-11.2/lib64

  Some of these libraries may not be found correctly.

-- Generating done
-- Build files have been written to: /home/a/Software/caffe/build
(base) a@ai:~/Software/caffe/build$ make all
[  1%] Running C++/Python protocol buffer compiler on /home/a/Software/caffe/src/caffe/proto/caffe.proto
Scanning dependencies of target caffeproto
[  1%] Building CXX object src/caffe/CMakeFiles/caffeproto.dir/__/__/include/caffe/proto/caffe.pb.cc.o
[  1%] Linking CXX static library ../../lib/libcaffeproto.a
[  1%] Built target caffeproto
[  1%] Building NVCC (Device) object src/caffe/CMakeFiles/cuda_compile_1.dir/util/cuda_compile_1_generated_math_functions.cu.o
In file included from /home/a/Software/caffe/src/caffe/util/math_functions.cu:1:
/usr/local/cuda-11.2/include/math_functions.h:54:2: warning: #warning "math_functions.h is an internal header file and must not be used directly.  This file will be removed in a future CUDA release.  Please use cuda_runtime_api.h or cuda_runtime.h instead." [-Wcpp]
/home/a/Software/caffe/include/caffe/util/cudnn.hpp: In function ‘const char* cudnnGetErrorString(cudnnStatus_t)’:
/home/a/Software/caffe/include/caffe/util/cudnn.hpp:21:8: warning: enumeration value ‘CUDNN_STATUS_VERSION_MISMATCH’ not handled in switch [-Wswitch]
   21 |   switch (status) {
      |        ^
[  1%] Building NVCC (Device) object src/caffe/CMakeFiles/cuda_compile_1.dir/layers/cuda_compile_1_generated_absval_layer.cu.o
/home/a/Software/caffe/include/caffe/util/cudnn.hpp: In function ‘const char* cudnnGetErrorString(cudnnStatus_t)’:
/home/a/Software/caffe/include/caffe/util/cudnn.hpp:21:8: warning: enumeration value ‘CUDNN_STATUS_VERSION_MISMATCH’ not handled in switch [-Wswitch]

            .
     .
     dozens of same error
     .
     .
     .
   21 |   switch (status) {
      |          ^
/home/a/Software/caffe/src/caffe/layers/cudnn_conv_layer.cpp: In member function ‘virtual void caffe::CuDNNConvolutionLayer<Dtype>::Reshape(const std::vector<caffe::Blob<Dtype>*>&, const std::vector<caffe::Blob<Dtype>*>&)’:
/home/a/Software/caffe/src/caffe/layers/cudnn_conv_layer.cpp:136:7: error: ‘CUDNN_CONVOLUTION_FWD_SPECIFY_WORKSPACE_LIMIT’ was not declared in this scope
  136 |       CUDNN_CONVOLUTION_FWD_SPECIFY_WORKSPACE_LIMIT,
      |       ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/a/Software/caffe/include/caffe/util/cudnn.hpp:15:28: note: in definition of macro ‘CUDNN_CHECK’
   15 |     cudnnStatus_t status = condition; \
      |                            ^~~~~~~~~
/home/a/Software/caffe/src/caffe/layers/cudnn_conv_layer.cpp:131:17: error: there are no arguments to ‘cudnnGetConvolutionForwardAlgorithm’ that depend on a template parameter, so a declaration of ‘cudnnGetConvolutionForwardAlgorithm’ must be available [-fpermissive]
  131 |     CUDNN_CHECK(cudnnGetConvolutionForwardAlgorithm(handle_[0],
      |                 ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/a/Software/caffe/include/caffe/util/cudnn.hpp:15:28: note: in definition of macro ‘CUDNN_CHECK’
   15 |     cudnnStatus_t status = condition; \
      |                            ^~~~~~~~~
/home/a/Software/caffe/src/caffe/layers/cudnn_conv_layer.cpp:131:17: note: (if you use ‘-fpermissive’, G++ will accept your code, but allowing the use of an undeclared name is deprecated)
  131 |     CUDNN_CHECK(cudnnGetConvolutionForwardAlgorithm(handle_[0],
      |                 ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/a/Software/caffe/include/caffe/util/cudnn.hpp:15:28: note: in definition of macro ‘CUDNN_CHECK’
   15 |     cudnnStatus_t status = condition; \
      |                            ^~~~~~~~~
/home/a/Software/caffe/src/caffe/layers/cudnn_conv_layer.cpp:151:11: error: ‘CUDNN_CONVOLUTION_BWD_FILTER_SPECIFY_WORKSPACE_LIMIT’ was not declared in this scope
  151 |           CUDNN_CONVOLUTION_BWD_FILTER_SPECIFY_WORKSPACE_LIMIT,
      |           ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/a/Software/caffe/include/caffe/util/cudnn.hpp:15:28: note: in definition of macro ‘CUDNN_CHECK’
   15 |     cudnnStatus_t status = condition; \
      |                            ^~~~~~~~~
/home/a/Software/caffe/src/caffe/layers/cudnn_conv_layer.cpp:149:17: error: there are no arguments to ‘cudnnGetConvolutionBackwardFilterAlgorithm’ that depend on a template parameter, so a declaration of ‘cudnnGetConvolutionBackwardFilterAlgorithm’ must be available [-fpermissive]
  149 |     CUDNN_CHECK(cudnnGetConvolutionBackwardFilterAlgorithm(handle_[0],
      |                 ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/a/Software/caffe/include/caffe/util/cudnn.hpp:15:28: note: in definition of macro ‘CUDNN_CHECK’
   15 |     cudnnStatus_t status = condition; \
      |                            ^~~~~~~~~
/home/a/Software/caffe/src/caffe/layers/cudnn_conv_layer.cpp:162:11: error: ‘CUDNN_CONVOLUTION_BWD_DATA_SPECIFY_WORKSPACE_LIMIT’ was not declared in this scope
  162 |           CUDNN_CONVOLUTION_BWD_DATA_SPECIFY_WORKSPACE_LIMIT,
      |           ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/a/Software/caffe/include/caffe/util/cudnn.hpp:15:28: note: in definition of macro ‘CUDNN_CHECK’
   15 |     cudnnStatus_t status = condition; \
      |                            ^~~~~~~~~
/home/a/Software/caffe/src/caffe/layers/cudnn_conv_layer.cpp:160:17: error: there are no arguments to ‘cudnnGetConvolutionBackwardDataAlgorithm’ that depend on a template parameter, so a declaration of ‘cudnnGetConvolutionBackwardDataAlgorithm’ must be available [-fpermissive]
  160 |     CUDNN_CHECK(cudnnGetConvolutionBackwardDataAlgorithm(handle_[0],
      |                 ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/a/Software/caffe/include/caffe/util/cudnn.hpp:15:28: note: in definition of macro ‘CUDNN_CHECK’
   15 |     cudnnStatus_t status = condition; \
      |                            ^~~~~~~~~
/home/a/Software/caffe/src/caffe/layers/cudnn_conv_layer.cpp: In instantiation of ‘void caffe::CuDNNConvolutionLayer<Dtype>::Reshape(const std::vector<caffe::Blob<Dtype>*>&, const std::vector<caffe::Blob<Dtype>*>&) [with Dtype = float]’:
/home/a/Software/caffe/src/caffe/layers/cudnn_conv_layer.cpp:266:1:   required from here
/home/a/Software/caffe/src/caffe/layers/cudnn_conv_layer.cpp:131:52: error: ‘cudnnGetConvolutionForwardAlgorithm’ was not declared in this scope; did you mean ‘cudnnGetConvolutionForwardAlgorithm_v7’?
  131 |     CUDNN_CHECK(cudnnGetConvolutionForwardAlgorithm(handle_[0],
      |                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~
  132 |       bottom_descs_[i],
      |       ~~~~~~~~~~~~~~~~~
  133 |       filter_desc_,
      |       ~~~~~~~~~~~~~
  134 |       conv_descs_[i],
      |       ~~~~~~~~~~~~~~~
  135 |       top_descs_[i],
      |       ~~~~~~~~~~~~~~
  136 |       CUDNN_CONVOLUTION_FWD_SPECIFY_WORKSPACE_LIMIT,
      |       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  137 |       workspace_limit_bytes,
      |       ~~~~~~~~~~~~~~~~~~~~~~
  138 |       &fwd_algo_[i]));
      |       ~~~~~~~~~~~~~~
/home/a/Software/caffe/include/caffe/util/cudnn.hpp:15:28: note: in definition of macro ‘CUDNN_CHECK’
   15 |     cudnnStatus_t status = condition; \
      |                            ^~~~~~~~~
/home/a/Software/caffe/src/caffe/layers/cudnn_conv_layer.cpp:149:59: error: ‘cudnnGetConvolutionBackwardFilterAlgorithm’ was not declared in this scope; did you mean ‘cudnnGetConvolutionBackwardFilterAlgorithm_v7’?
  149 |     CUDNN_CHECK(cudnnGetConvolutionBackwardFilterAlgorithm(handle_[0],
      |                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~
  150 |           bottom_descs_[i], top_descs_[i], conv_descs_[i], filter_desc_,
      |           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  151 |           CUDNN_CONVOLUTION_BWD_FILTER_SPECIFY_WORKSPACE_LIMIT,
      |           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  152 |           workspace_limit_bytes, &bwd_filter_algo_[i]) );
      |           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/a/Software/caffe/include/caffe/util/cudnn.hpp:15:28: note: in definition of macro ‘CUDNN_CHECK’
   15 |     cudnnStatus_t status = condition; \
      |                            ^~~~~~~~~
/home/a/Software/caffe/src/caffe/layers/cudnn_conv_layer.cpp:160:57: error: ‘cudnnGetConvolutionBackwardDataAlgorithm’ was not declared in this scope; did you mean ‘cudnnGetConvolutionBackwardDataAlgorithm_v7’?
  160 |     CUDNN_CHECK(cudnnGetConvolutionBackwardDataAlgorithm(handle_[0],
      |                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~
  161 |           filter_desc_, top_descs_[i], conv_descs_[i], bottom_descs_[i],
      |           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  162 |           CUDNN_CONVOLUTION_BWD_DATA_SPECIFY_WORKSPACE_LIMIT,
      |           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  163 |         workspace_limit_bytes, &bwd_data_algo_[i]));
      |         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/a/Software/caffe/include/caffe/util/cudnn.hpp:15:28: note: in definition of macro ‘CUDNN_CHECK’
   15 |     cudnnStatus_t status = condition; \
      |                            ^~~~~~~~~
/home/a/Software/caffe/src/caffe/layers/cudnn_conv_layer.cpp: In instantiation of ‘void caffe::CuDNNConvolutionLayer<Dtype>::Reshape(const std::vector<caffe::Blob<Dtype>*>&, const std::vector<caffe::Blob<Dtype>*>&) [with Dtype = double]’:
/home/a/Software/caffe/src/caffe/layers/cudnn_conv_layer.cpp:266:1:   required from here
/home/a/Software/caffe/src/caffe/layers/cudnn_conv_layer.cpp:131:52: error: ‘cudnnGetConvolutionForwardAlgorithm’ was not declared in this scope; did you mean ‘cudnnGetConvolutionForwardAlgorithm_v7’?
  131 |     CUDNN_CHECK(cudnnGetConvolutionForwardAlgorithm(handle_[0],
      |                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~
  132 |       bottom_descs_[i],
      |       ~~~~~~~~~~~~~~~~~
  133 |       filter_desc_,
      |       ~~~~~~~~~~~~~
  134 |       conv_descs_[i],
      |       ~~~~~~~~~~~~~~~
  135 |       top_descs_[i],
      |       ~~~~~~~~~~~~~~
  136 |       CUDNN_CONVOLUTION_FWD_SPECIFY_WORKSPACE_LIMIT,
      |       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  137 |       workspace_limit_bytes,
      |       ~~~~~~~~~~~~~~~~~~~~~~
  138 |       &fwd_algo_[i]));
      |       ~~~~~~~~~~~~~~
/home/a/Software/caffe/include/caffe/util/cudnn.hpp:15:28: note: in definition of macro ‘CUDNN_CHECK’
   15 |     cudnnStatus_t status = condition; \
      |                            ^~~~~~~~~
/home/a/Software/caffe/src/caffe/layers/cudnn_conv_layer.cpp:149:59: error: ‘cudnnGetConvolutionBackwardFilterAlgorithm’ was not declared in this scope; did you mean ‘cudnnGetConvolutionBackwardFilterAlgorithm_v7’?
  149 |     CUDNN_CHECK(cudnnGetConvolutionBackwardFilterAlgorithm(handle_[0],
      |                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~
  150 |           bottom_descs_[i], top_descs_[i], conv_descs_[i], filter_desc_,
      |           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  151 |           CUDNN_CONVOLUTION_BWD_FILTER_SPECIFY_WORKSPACE_LIMIT,
      |           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  152 |           workspace_limit_bytes, &bwd_filter_algo_[i]) );
      |           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/a/Software/caffe/include/caffe/util/cudnn.hpp:15:28: note: in definition of macro ‘CUDNN_CHECK’
   15 |     cudnnStatus_t status = condition; \
      |                            ^~~~~~~~~
/home/a/Software/caffe/src/caffe/layers/cudnn_conv_layer.cpp:160:57: error: ‘cudnnGetConvolutionBackwardDataAlgorithm’ was not declared in this scope; did you mean ‘cudnnGetConvolutionBackwardDataAlgorithm_v7’?
  160 |     CUDNN_CHECK(cudnnGetConvolutionBackwardDataAlgorithm(handle_[0],
      |                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~
  161 |           filter_desc_, top_descs_[i], conv_descs_[i], bottom_descs_[i],
      |           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  162 |           CUDNN_CONVOLUTION_BWD_DATA_SPECIFY_WORKSPACE_LIMIT,
      |           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  163 |         workspace_limit_bytes, &bwd_data_algo_[i]));
      |         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/a/Software/caffe/include/caffe/util/cudnn.hpp:15:28: note: in definition of macro ‘CUDNN_CHECK’
   15 |     cudnnStatus_t status = condition; \
      |                            ^~~~~~~~~
make[2]: *** [src/caffe/CMakeFiles/caffe.dir/build.make:764: src/caffe/CMakeFiles/caffe.dir/layers/cudnn_conv_layer.cpp.o] Error 1
make[1]: *** [CMakeFiles/Makefile2:401: src/caffe/CMakeFiles/caffe.dir/all] Error 2
make: *** [Makefile:130: all] Error 2
(base) a@ai:~/Software/caffe/build$ cd ..


来源: stackexchange

问:
Undefined reference to vtable
When building my C++ program, I'm getting the error message

undefined reference to 'vtable...

What is the cause of this problem? How do I fix it?

It so happens that I'm getting the error for the following code (The class in question is CGameModule.) and I cannot for the life of me understand what the problem is. At first, I thought it was related to forgetting to give a virtual function a body, but as far as I understand, everything is all here. The inheritance chain is a little long, but here is the related source code. I'm not sure what other information I should provide.

Note: The constructor is where this error is happening, it'd seem.

My code:

```<code>class CGameModule : public CDasherModule {
 public:
  CGameModule(Dasher::CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherInterfaceBase *pInterface, ModuleID_t iID, const char *szName)
  : CDasherModule(pEventHandler, pSettingsStore, iID, 0, szName)
  {
      g_pLogger->Log("Inside game module constructor");
      m_pInterface = pInterface;
  }

  virtual ~CGameModule() {};

  std::string GetTypedTarget();

  std::string GetUntypedTarget();

  bool DecorateView(CDasherView *pView) {
      //g_pLogger->Log("Decorating the view");
      return false;
  }

  void SetDasherModel(CDasherModel *pModel) { m_pModel = pModel; }

  virtual void HandleEvent(Dasher::CEvent *pEvent);

 private:

  CDasherNode *pLastTypedNode;

  CDasherNode *pNextTargetNode;

  std::string m_sTargetString;

  size_t m_stCurrentStringPos;

  CDasherModel *m_pModel;

  CDasherInterfaceBase *m_pInterface;
};
</code>```

Inherits from...

```<code>class CDasherModule;
typedef std::vector<CDasherModule*>::size_type ModuleID_t;

/// \ingroup Core
/// @{
class CDasherModule : public Dasher::CDasherComponent {
 public:
  CDasherModule(Dasher::CEventHandler * pEventHandler, CSettingsStore * pSettingsStore, ModuleID_t iID, int iType, const char *szName);

  virtual ModuleID_t GetID();
  virtual void SetID(ModuleID_t);
  virtual int GetType();
  virtual const char *GetName();

  virtual bool GetSettings(SModuleSettings **pSettings, int *iCount) {
    return false;
  };

 private:
  ModuleID_t m_iID;
  int m_iType;
  const char *m_szName;
};
</code>```

Which inherits from....

```<code>namespace Dasher {
  class CEvent;
  class CEventHandler;
  class CDasherComponent;
};

/// \ingroup Core
/// @{
class Dasher::CDasherComponent {
 public:
  CDasherComponent(Dasher::CEventHandler* pEventHandler, CSettingsStore* pSettingsStore);
  virtual ~CDasherComponent();

  void InsertEvent(Dasher::CEvent * pEvent);
  virtual void HandleEvent(Dasher::CEvent * pEvent) {};

  bool GetBoolParameter(int iParameter) const;
  void SetBoolParameter(int iParameter, bool bValue) const;

  long GetLongParameter(int iParameter) const;
  void SetLongParameter(int iParameter, long lValue) const;

  std::string GetStringParameter(int iParameter) const;
  void        SetStringParameter(int iParameter, const std::string & sValue) const;

  ParameterType   GetParameterType(int iParameter) const;
  std::string     GetParameterName(int iParameter) const;

 protected:
  Dasher::CEventHandler *m_pEventHandler;
  CSettingsStore *m_pSettingsStore;
};
/// @}

#endif
</code>```

答:
FWIW I was able to avoid errors like these:

```<code> ld: /usr/local/lib/libvmaf.a(svm.cpp.o):(.data.rel.ro._ZTI7QMatrix[_ZTI7QMatrix]+0x0): undefined reference to `vtable for __cxxabiv1::__class_type_info'
</code>```

When linking a "C" project with a static library from a "C++" project, by adding -lstdc++ to the linking parameters.  So it's gcc -lstdc++ now it works.

Most common way is to add the -lstdc++ to the libraries pkgconfig .pc file Library list.  Or link with g++ instead.

ContentLicense: CC BY-SA 4.0

Title: Undefined reference to vtable

Body:
When building my C++ program, I'm getting the error message

undefined reference to 'vtable...

What is the cause of this problem? How do I fix it?

It so happens that I'm getting the error for the following code (The class in question is CGameModule.) and I cannot for the life of me understand what the problem is. At first, I thought it was related to forgetting to give a virtual function a body, but as far as I understand, everything is all here. The inheritance chain is a little long, but here is the related source code. I'm not sure what other information I should provide.

Note: The constructor is where this error is happening, it'd seem.

My code:

class CGameModule : public CDasherModule {
 public:
  CGameModule(Dasher::CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherInterfaceBase *pInterface, ModuleID_t iID, const char *szName)
  : CDasherModule(pEventHandler, pSettingsStore, iID, 0, szName)
  {
      g_pLogger->Log("Inside game module constructor");
      m_pInterface = pInterface;
  }

  virtual ~CGameModule() {};

  std::string GetTypedTarget();

  std::string GetUntypedTarget();

  bool DecorateView(CDasherView *pView) {
      //g_pLogger->Log("Decorating the view");
      return false;
  }

  void SetDasherModel(CDasherModel *pModel) { m_pModel = pModel; }

  virtual void HandleEvent(Dasher::CEvent *pEvent);

 private:

  CDasherNode *pLastTypedNode;

  CDasherNode *pNextTargetNode;

  std::string m_sTargetString;

  size_t m_stCurrentStringPos;

  CDasherModel *m_pModel;

  CDasherInterfaceBase *m_pInterface;
};

Inherits from...

class CDasherModule;
typedef std::vector<CDasherModule*>::size_type ModuleID_t;

/// \ingroup Core
/// @{
class CDasherModule : public Dasher::CDasherComponent {
 public:
  CDasherModule(Dasher::CEventHandler * pEventHandler, CSettingsStore * pSettingsStore, ModuleID_t iID, int iType, const char *szName);

  virtual ModuleID_t GetID();
  virtual void SetID(ModuleID_t);
  virtual int GetType();
  virtual const char *GetName();

  virtual bool GetSettings(SModuleSettings **pSettings, int *iCount) {
    return false;
  };

 private:
  ModuleID_t m_iID;
  int m_iType;
  const char *m_szName;
};

Which inherits from....

namespace Dasher {
  class CEvent;
  class CEventHandler;
  class CDasherComponent;
};

/// \ingroup Core
/// @{
class Dasher::CDasherComponent {
 public:
  CDasherComponent(Dasher::CEventHandler* pEventHandler, CSettingsStore* pSettingsStore);
  virtual ~CDasherComponent();

  void InsertEvent(Dasher::CEvent * pEvent);
  virtual void HandleEvent(Dasher::CEvent * pEvent) {};

  bool GetBoolParameter(int iParameter) const;
  void SetBoolParameter(int iParameter, bool bValue) const;

  long GetLongParameter(int iParameter) const;
  void SetLongParameter(int iParameter, long lValue) const;

  std::string GetStringParameter(int iParameter) const;
  void        SetStringParameter(int iParameter, const std::string & sValue) const;

  ParameterType   GetParameterType(int iParameter) const;
  std::string     GetParameterName(int iParameter) const;

 protected:
  Dasher::CEventHandler *m_pEventHandler;
  CSettingsStore *m_pSettingsStore;
};
/// @}

#endif

Body:
FWIW I was able to avoid errors like these:

 ld: /usr/local/lib/libvmaf.a(svm.cpp.o):(.data.rel.ro._ZTI7QMatrix[_ZTI7QMatrix]+0x0): undefined reference to `vtable for __cxxabiv1::__class_type_info'

When linking a "C" project with a static library from a "C++" project, by adding -lstdc++ to the linking parameters.  So it's gcc -lstdc++ now it works.

Most common way is to add the -lstdc++ to the libraries pkgconfig .pc file Library list.  Or link with g++ instead.


问:
Passing a child component(drop down) to the parent component with React-Hook-Forms: ref is not a prop & no values saved when submitted
I have this drop-down (select) component named Size as a child component and nested useFieldArray in the parent component I am  receiving warnings every time I submit it and no values are being displayed in the console. What is happening and how can I fix this?

These are the errors:

Warning: Size: ref is not a prop. Trying to access it will result in
undefined being returned. If you need to access the same value
within the child component, you should pass it as a different prop.

Field is missing name attribute …

Link to codesandbox:
https://codesandbox.io/s/react-hook-form-usefieldarray-nested-arrays-forked-vjwbp?file=/src/Drop_drowns/Size.js

Size.js

```<code>import { InputLabel, MenuItem, FormControl, Select } from "@mui/material";

const Size = ({ name, ref, defaultValue }) => {
  return (
    <FormControl fullWidth variant="filled">
      <InputLabel id="Size Label">Size</InputLabel>
      <Select
        labelId="Size"
        id="size"
        name={name}
        label="Product"
        ref={ref}
        defaultValue={defaultValue}
      >
        <MenuItem value="S">Small</MenuItem>
        <MenuItem value="M">Medium</MenuItem>
        <MenuItem value="L">Large</MenuItem>
      </Select>
    </FormControl>
  );
};

export default Size;
</code>```

Nested Field Array:

```<code>import React from "react";
import { useFieldArray } from "react-hook-form";
import Size from "./Drop_drowns/Size";
import { TextField } from "@mui/material";

export default ({ nestIndex, control, register }) => {
  const { fields, remove, append } = useFieldArray({
    control,
    name: `test[${nestIndex}].nestedArray`
  });

  return (
    <div>
      {fields.map((item, k) => {
        return (
          <div key={item.id} style={{ marginLeft: 20 }}>
            <label>Colors:</label>
            <Size
              name={`test[${nestIndex}].nestedArray[${k}].field1`}
              ref={register({ required: true })}
              defaultValue={item.field1}
              style={{ marginRight: "25px" }}
            />
            {/* <input
              name={`test[${nestIndex}].nestedArray[${k}].field1`}
              ref={register({ required: true })}
              defaultValue={item.field1}
              style={{ marginRight: "25px" }}
            /> */}

            <TextField
              name={`test[${nestIndex}].nestedArray[${k}].field2`}
              ref={register()}
              defaultValue={item.field2}
            />

            <TextField
              name={`test[${nestIndex}].nestedArray[${k}].field3`}
              ref={register()}
              defaultValue={item.field3}
            />
            <button type="button" onClick={() => remove(k)}>
              Delete Colors
            </button>
          </div>
        );
      })}

      <button
        type="button"
        onClick={() =>
          append({
            field1: "field1",
            field2: "field2"
          })
        }
      >
        Add Colors
      </button>

      <hr />
    </div>
  );
};
</code>```

fieldArray:

```<code>import React from "react";
import { useFieldArray } from "react-hook-form";
import NestedArray from "./nestedFieldArray";
import { TextField } from "@mui/material";

let renderCount = 0;

export default function Fields({ control, register, setValue, getValues }) {
  const { fields, append, remove, prepends } = useFieldArray({
    control,
    name: "test"
  });

  renderCount++;

  return (
    <>
      <ul>
        {fields.map((item, index) => {
          return (
            <li key={item.id}>
              <TextField
                name={`test[${index}].name`}
                ref={register()}
                defaultValue={item.name}
              />

              <button type="button" onClick={() => remove(index)}>
                Delete
              </button>
              <NestedArray nestIndex={index} {...{ control, register }} />
            </li>
          );
        })}
      </ul>

      <section>
        <button
          type="button"
          onClick={() => {
            append({ name: "append" });
          }}
        >
          Add product
        </button>

        {/* <button
          type="button"
          onClick={() => {
            setValue("test", [
              ...getValues().test,
              {
                name: "append",
                nestedArray: [{ field1: "append", field2: "append" }]
              }
            ]);
          }}
        >
          update product
        </button> */}
      </section>

      <span className="counter">Render Count: {renderCount}</span>
    </>
  );
}
</code>```

index.js

```<code>import React from "react";
import { useForm } from "react-hook-form";
import FieldArray from "./fieldArray";
import ReactDOM from "react-dom";

import "./styles.css";

const defaultValues = {
  test: [
    {
      product: "",
      nestedArray: [{ field1: "", field2: "", field3: "" }]
    },
    {
      product: "",
      nestedArray: [{ field1: "", field2: "", field3: "" }]
    }
  ]
};

function App() {
  const {
    control,
    register,
    handleSubmit,
    getValues,
    errors,
    reset,
    setValue
  } = useForm({
    defaultValues
  });
  const onSubmit = (data) => console.log("data", data);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <h1>Array of Array Fields</h1>
      <p>
        The following example demonstrate the ability of building nested array
        fields.
      </p>

      <FieldArray
        {...{ control, register, defaultValues, getValues, setValue, errors }}
      />

      <button type="button" onClick={() => reset(defaultValues)}>
        Reset
      </button>

      <input type="submit" />
    </form>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
</code>```

答:
You are attempting to pass a prop called ref to a functional component. You can't pass refs to functional components. Also, what you're trying to pass isn't a ref. See https://reactjs.org/docs/refs-and-the-dom.html#adding-a-ref-to-a-dom-element for an example of what I'm talking about. If you rename the prop ref to reference, referral, referenceMaterial, etc, you will get rid of the issue. The following error in your console on the sandbox will let you know this as well.

```<code>Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
</code>```

Just change your props to a different, more descriptive name and you'll be in business again.

Edit:
Also,
Edit:
Also, I see that you're passing a method register into refer. I am not sure if you instantly need a result that's being passed as props. If so, you're good. If you need to pass the function, you have to wrap it with an anonymous function to ensure it isn't immediately called:

```<code><Element props={() => {register({ required: true })}} />
</code>```

Once you've wrapped the function, it won't instantly be called.
When you pass register, you are passing the function.
When you pass register(), you are passing the result that gets returned because the function is immediately being called.
It's all about the parentheses. If the parentheses are there, it is invoked immediately.

Body:
I have this drop-down (select) component named Size as a child component and nested useFieldArray in the parent component I am  receiving warnings every time I submit it and no values are being displayed in the console. What is happening and how can I fix this?

These are the errors:

Warning: Size: ref is not a prop. Trying to access it will result in
undefined being returned. If you need to access the same value
within the child component, you should pass it as a different prop.

Field is missing name attribute …

Link to codesandbox:
https://codesandbox.io/s/react-hook-form-usefieldarray-nested-arrays-forked-vjwbp?file=/src/Drop_drowns/Size.js

Size.js

import { InputLabel, MenuItem, FormControl, Select } from "@mui/material";

const Size = ({ name, ref, defaultValue }) => {
  return (
    <FormControl fullWidth variant="filled">
      <InputLabel id="Size Label">Size</InputLabel>
      <Select
        labelId="Size"
        id="size"
        name={name}
        label="Product"
        ref={ref}
        defaultValue={defaultValue}
      >
        <MenuItem value="S">Small</MenuItem>
        <MenuItem value="M">Medium</MenuItem>
        <MenuItem value="L">Large</MenuItem>
      </Select>
    </FormControl>
  );
};

export default Size;

Nested Field Array:

import React from "react";
import { useFieldArray } from "react-hook-form";
import Size from "./Drop_drowns/Size";
import { TextField } from "@mui/material";

export default ({ nestIndex, control, register }) => {
  const { fields, remove, append } = useFieldArray({
    control,
    name: `test[${nestIndex}].nestedArray`
  });

  return (

      {fields.map((item, k) => {
        return (

            Colors:
            <Size
              name={`test[${nestIndex}].nestedArray[${k}].field1`}
              ref={register({ required: true })}
              defaultValue={item.field1}
              style={{ marginRight: "25px" }}
            />
            {/* <input
              name={`test[${nestIndex}].nestedArray[${k}].field1`}
              ref={register({ required: true })}
              defaultValue={item.field1}
              style={{ marginRight: "25px" }}
            /> */}

            <TextField
              name={`test[${nestIndex}].nestedArray[${k}].field2`}
              ref={register()}
              defaultValue={item.field2}
            />

            <TextField
              name={`test[${nestIndex}].nestedArray[${k}].field3`}
              ref={register()}
              defaultValue={item.field3}
            />
            <button type="button" onClick={() => remove(k)}>
              Delete Colors
            </button>

        );
      })}

      <button
        type="button"
        onClick={() =>
          append({
            field1: "field1",
            field2: "field2"
          })
        }
      >
        Add Colors
      </button>

  );
};

fieldArray:

import React from "react";
import { useFieldArray } from "react-hook-form";
import NestedArray from "./nestedFieldArray";
import { TextField } from "@mui/material";

let renderCount = 0;

export default function Fields({ control, register, setValue, getValues }) {
  const { fields, append, remove, prepends } = useFieldArray({
    control,
    name: "test"
  });

  renderCount++;

  return (
    <>

        {fields.map((item, index) => {
          return (

              <TextField
                name={`test[${index}].name`}
                ref={register()}
                defaultValue={item.name}
              />

              <button type="button" onClick={() => remove(index)}>
                Delete
              </button>
              <NestedArray nestIndex={index} {...{ control, register }} />

          );
        })}

        <button
          type="button"
          onClick={() => {
            append({ name: "append" });
          }}
        >
          Add product
        </button>

        {/* <button
          type="button"
          onClick={() => {
            setValue("test", [
              ...getValues().test,
              {
                name: "append",
                nestedArray: [{ field1: "append", field2: "append" }]
              }
            ]);
          }}
        >
          update product
        </button> */}

      Render Count: {renderCount}
    </>
  );
}

index.js

import React from "react";
import { useForm } from "react-hook-form";
import FieldArray from "./fieldArray";
import ReactDOM from "react-dom";

import "./styles.css";

const defaultValues = {
  test: [
    {
      product: "",
      nestedArray: [{ field1: "", field2: "", field3: "" }]
    },
    {
      product: "",
      nestedArray: [{ field1: "", field2: "", field3: "" }]
    }
  ]
};

function App() {
  const {
    control,
    register,
    handleSubmit,
    getValues,
    errors,
    reset,
    setValue
  } = useForm({
    defaultValues
  });
  const onSubmit = (data) => console.log("data", data);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>

Array of Array Fields

        The following example demonstrate the ability of building nested array
        fields.

      <FieldArray
        {...{ control, register, defaultValues, getValues, setValue, errors }}
      />

      <button type="button" onClick={() => reset(defaultValues)}>
        Reset
      </button>

      <input type="submit" />
    </form>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Body:
You are attempting to pass a prop called ref to a functional component. You can't pass refs to functional components. Also, what you're trying to pass isn't a ref. See https://reactjs.org/docs/refs-and-the-dom.html#adding-a-ref-to-a-dom-element for an example of what I'm talking about. If you rename the prop ref to reference, referral, referenceMaterial, etc, you will get rid of the issue. The following error in your console on the sandbox will let you know this as well.

Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

Just change your props to a different, more descriptive name and you'll be in business again.

Edit:
Also,
Edit:
Also, I see that you're passing a method register into refer. I am not sure if you instantly need a result that's being passed as props. If so, you're good. If you need to pass the function, you have to wrap it with an anonymous function to ensure it isn't immediately called:

<Element props={() => {register({ required: true })}} />

Once you've wrapped the function, it won't instantly be called.
When you pass register, you are passing the function.
When you pass register(), you are passing the result that gets returned because the function is immediately being called.
It's all about the parentheses. If the parentheses are there, it is invoked immediately.


问:
C# Permutation of an array of arraylists?
I have an ArrayList[] myList and I am trying to create a list of all the permutations of the values in the arrays.

EXAMPLE: (all values are strings)

```<code>myList[0] = { "1", "5", "3", "9" };
myList[1] = { "2", "3" };
myList[2] = { "93" };
</code>```

The count of myList can be varied so its length is not known beforehand.

I would like to be able to generate a list of all the permutations similar to the following (but with some additional formatting).

```<code>1 2 93
1 3 93
5 2 93
5 3 93
3 2 93
3 3 93
9 2 93
9 3 93
</code>```

Does this make sense of what I am trying to accomplish?  I can't seem to come up with a good method for doing this, (if any).

Edit:

I am not sure if recursion would interfere with my desire to format the output in my own manner. Sorry I did not mention before what my formatting was.

I want to end up building a string[] array of all the combinations that follows the format like below:

for the "1 2 93" permutation

I want the output to be "val0=1;val1=2;val2=93;"

I will experiment with recursion for now. Thank you DrJokepu

答:
This will work no matter how many arrays you add to your myList:

```<code>        static void Main(string[] args)
        {
            string[][] myList = new string[3][];
            myList[0] = new string[] { "1", "5", "3", "9" };
            myList[1] = new string[] { "2", "3" };
            myList[2] = new string[] { "93" };

            List<string> permutations = new List<string>(myList[0]);

            for (int i = 1; i < myList.Length; ++i)
            {
                permutations = RecursiveAppend(permutations, myList[i]);
            }

            //at this point the permutations variable contains all permutations

        }

        static List<string> RecursiveAppend(List<string> priorPermutations, string[] additions)
        {
            List<string> newPermutationsResult = new List<string>();
            foreach (string priorPermutation in priorPermutations)
            {
                foreach (string addition in additions)
                {
                    newPermutationsResult.Add(priorPermutation + ":" + addition);
                }
            }
            return newPermutationsResult;
        }
</code>```

Note that it's not really recursive.  Probably a misleading function name.

Here is a version that adheres to your new requirements.  Note the section where I output to console, this is where you can do your own formatting:

```<code>static void Main(string[] args)
        {
            string[][] myList = new string[3][];
            myList[0] = new string[] { "1", "5", "3", "9" };
            myList[1] = new string[] { "2", "3" };
            myList[2] = new string[] { "93" };

            List<List<string>> permutations = new List<List<string>>();

            foreach (string init in myList[0])
            {
                List<string> temp = new List<string>();
                temp.Add(init);
                permutations.Add(temp);
            }

            for (int i = 1; i < myList.Length; ++i)
            {
                permutations = RecursiveAppend(permutations, myList[i]);
            }

            //at this point the permutations variable contains all permutations

            foreach (List<string> list in permutations)
            {
                foreach (string item in list)
                {
                    Console.Write(item + ":");
                }
                Console.WriteLine();
            }

        }

        static List<List<string>> RecursiveAppend(List<List<string>> priorPermutations, string[] additions)
        {
            List<List<string>> newPermutationsResult = new List<List<string>>();
            foreach (List<string> priorPermutation in priorPermutations)
            {
                foreach (string addition in additions)
                {
                    List<string> priorWithAddition = new List<string>(priorPermutation);
                    priorWithAddition.Add(addition);
                    newPermutationsResult.Add(priorWithAddition);
                }
            }
            return newPermutationsResult;
        }
</code>```

OwnerDisplayName: TaRDy

LastEditorDisplayName: Quintin Robinson

ContentLicense: CC BY-SA 2.5

Body:
I have an ArrayList[] myList and I am trying to create a list of all the permutations of the values in the arrays.

EXAMPLE: (all values are strings)

myList[0] = { "1", "5", "3", "9" };
myList[1] = { "2", "3" };
myList[2] = { "93" };

The count of myList can be varied so its length is not known beforehand.

I would like to be able to generate a list of all the permutations similar to the following (but with some additional formatting).

1 2 93
1 3 93
5 2 93
5 3 93
3 2 93
3 3 93
9 2 93
9 3 93

Does this make sense of what I am trying to accomplish?  I can't seem to come up with a good method for doing this, (if any).

Edit:

I am not sure if recursion would interfere with my desire to format the output in my own manner. Sorry I did not mention before what my formatting was.

I want to end up building a string[] array of all the combinations that follows the format like below:

for the "1 2 93" permutation

I want the output to be "val0=1;val1=2;val2=93;"

I will experiment with recursion for now. Thank you DrJokepu

Body:
This will work no matter how many arrays you add to your myList:

        static void Main(string[] args)
        {
            string[][] myList = new string[3][];
            myList[0] = new string[] { "1", "5", "3", "9" };
            myList[1] = new string[] { "2", "3" };
            myList[2] = new string[] { "93" };

            List<string> permutations = new List<string>(myList[0]);

            for (int i = 1; i < myList.Length; ++i)
            {
                permutations = RecursiveAppend(permutations, myList[i]);
            }

            //at this point the permutations variable contains all permutations

        }

        static List<string> RecursiveAppend(List<string> priorPermutations, string[] additions)
        {
            List<string> newPermutationsResult = new List<string>();
            foreach (string priorPermutation in priorPermutations)
            {
                foreach (string addition in additions)
                {
                    newPermutationsResult.Add(priorPermutation + ":" + addition);
                }
            }
            return newPermutationsResult;
        }

Note that it's not really recursive.  Probably a misleading function name.

Here is a version that adheres to your new requirements.  Note the section where I output to console, this is where you can do your own formatting:

static void Main(string[] args)
        {
            string[][] myList = new string[3][];
            myList[0] = new string[] { "1", "5", "3", "9" };
            myList[1] = new string[] { "2", "3" };
            myList[2] = new string[] { "93" };

            List<List<string>> permutations = new List<List<string>>();

            foreach (string init in myList[0])
            {
                List<string> temp = new List<string>();
                temp.Add(init);
                permutations.Add(temp);
            }

            for (int i = 1; i < myList.Length; ++i)
            {
                permutations = RecursiveAppend(permutations, myList[i]);
            }

            //at this point the permutations variable contains all permutations

            foreach (List<string> list in permutations)
            {
                foreach (string item in list)
                {
                    Console.Write(item + ":");
                }
                Console.WriteLine();
            }

        }

        static List<List<string>> RecursiveAppend(List<List<string>> priorPermutations, string[] additions)
        {
            List<List<string>> newPermutationsResult = new List<List<string>>();
            foreach (List<string> priorPermutation in priorPermutations)
            {
                foreach (string addition in additions)
                {
                    List<string> priorWithAddition = new List<string>(priorPermutation);
                    priorWithAddition.Add(addition);
                    newPermutationsResult.Add(priorWithAddition);
                }
            }
            return newPermutationsResult;
        }

OwnerDisplayName: aaronls

LastEditorDisplayName: aaronls


问:
how to know the full path of new created file?
see i have make one program which create one new file just using

```<code>fopen()
</code>```

Now i want to print full path of that file's in ma program.

How is that possible in linux with c programming?

答:
Standard C by itself provides no way to do this, actually. But the POSIX standard has getcwd. What you would do is append the path used to create the file to the working directory path obtained from getcwd -- unless, of course, the path used to create the file is an absolute path.

Alternatively, you could use realpath.

ContentLicense: CC BY-SA 3.0

Body:
see i have make one program which create one new file just using

fopen()

Now i want to print full path of that file's in ma program.

How is that possible in linux with c programming?


问:
Android Bluetooth (BLE) corrupted data on onCharacteristicChanged
My app do the following:

It sends a command with onDescriptorWrite to the BT device.

As soon the BT device gets this command it starts transferring data to the Android phone.

Android's onCharacteristicChanged is catching all the data sent from the BT device.

After all the data is transferred the Android app writes it to a file.

I've tested it and everything works totally perfect on a Samsung (Android 11), a OnePlus (Android 11), and a Xiaomi (Android 9), but the  data coming from onCharacteristicChanged is getting corrupted on a Nokia (Android 11).

This test example shows the transferred data wrote into a file with a checksum. As you can see I get the very same bytes on a Xiaomi, but on the Nokia it sometimes gets corrupted.

```<code>Tested on Xiaomi MiA1 (Android 9)

File_MD5: The right file MD5 -> AE36F08213B25B5E0EE19425257D0D85

File_MD5: Measurement file MD5: AE36F08213B25B5E0EE19425257D0D85 (ok)
File_MD5: Measurement file MD5: AE36F08213B25B5E0EE19425257D0D85 (ok)
File_MD5: Measurement file MD5: AE36F08213B25B5E0EE19425257D0D85 (ok)
File_MD5: Measurement file MD5: AE36F08213B25B5E0EE19425257D0D85 (ok)
File_MD5: Measurement file MD5: AE36F08213B25B5E0EE19425257D0D85 (ok)
File_MD5: Measurement file MD5: AE36F08213B25B5E0EE19425257D0D85 (ok)
File_MD5: Measurement file MD5: AE36F08213B25B5E0EE19425257D0D85 (ok)
File_MD5: Measurement file MD5: AE36F08213B25B5E0EE19425257D0D85 (ok)
File_MD5: Measurement file MD5: AE36F08213B25B5E0EE19425257D0D85 (ok)

Tested on Nokia 5.4 (Android 11)

File_MD5: The right file MD5 -> BCF704DD811A760B5602C20DEDB61AF8

File_MD5: Measurement file MD5: BCF704DD811A760B5602C20DEDB61AF8 (ok)
File_MD5: Measurement file MD5: E65A5D38EB3D8BF4E1AF5240DFBE1840 (ERROR)
File_MD5: Measurement file MD5: BCF704DD811A760B5602C20DEDB61AF8 (ok)
File_MD5: Measurement file MD5: BCF704DD811A760B5602C20DEDB61AF8 (ok)
File_MD5: Measurement file MD5: BCF704DD811A760B5602C20DEDB61AF8 (ok)
File_MD5: Measurement file MD5: BCF704DD811A760B5602C20DEDB61AF8 (ok)
File_MD5: Measurement file MD5: 0D3A577631A115FBAF3324A9B09244A8 (ERROR)
File_MD5: Measurement file MD5: A6FB1334D7AA1520F105ACB1EC1324C5 (ERROR)
File_MD5: Measurement file MD5: BCF704DD811A760B5602C20DEDB61AF8 (ok)
File_MD5: Measurement file MD5: BCF704DD811A760B5602C20DEDB61AF8 (ok)
</code>```

I'm absolutely standing incomprehensibly in front of this issue, yet another one of Android's fragmented and unreliable ecosystem.

I've tried the following:

Setting my BluetoothGatt instance to CONNECTION_PRIORITY_HIGH mode with requestConnectionPriority

Using a synchronized data container in onCharacteristicChanged in case if this is some multiple thread writing the same container type of error.

None of them helped.

Any insights?

E D I T:

My coworker made a firmware which simply sends incrementing numbers. As you can see within the red area, the data is corrupted, even with Nordic's own nRF toolbox app.

Should I be worried?

That means this Nokia is just doesn't work and that is it? Can this be a hardware issue for only this device?

答:
Seems like there are some differences in the realisation on that smartphone.   Try to do these things:

Put each chunks of the data (retrieved from onCharacteristicChanged) to a thread safe collection. It'll be better to wrap each chunk in a structure ({data: ByteArray, device: *, something else...}).

Handle each chunk in a background thread to avoid the UI freezing.
The main reason to do it, some devices are actively using byte caches inside and that could corrupt the data, we should copy bytes from onCharacteristicChanged as soon as possible and them handle in a convenient way on our own thread.

Body:
My app do the following:

It sends a command with onDescriptorWrite to the BT device.

As soon the BT device gets this command it starts transferring data to the Android phone.

Android's onCharacteristicChanged is catching all the data sent from the BT device.

After all the data is transferred the Android app writes it to a file.

I've tested it and everything works totally perfect on a Samsung (Android 11), a OnePlus (Android 11), and a Xiaomi (Android 9), but the  data coming from onCharacteristicChanged is getting corrupted on a Nokia (Android 11).

This test example shows the transferred data wrote into a file with a checksum. As you can see I get the very same bytes on a Xiaomi, but on the Nokia it sometimes gets corrupted.

Tested on Xiaomi MiA1 (Android 9)

File_MD5: The right file MD5 -> AE36F08213B25B5E0EE19425257D0D85

File_MD5: Measurement file MD5: AE36F08213B25B5E0EE19425257D0D85 (ok)
File_MD5: Measurement file MD5: AE36F08213B25B5E0EE19425257D0D85 (ok)
File_MD5: Measurement file MD5: AE36F08213B25B5E0EE19425257D0D85 (ok)
File_MD5: Measurement file MD5: AE36F08213B25B5E0EE19425257D0D85 (ok)
File_MD5: Measurement file MD5: AE36F08213B25B5E0EE19425257D0D85 (ok)
File_MD5: Measurement file MD5: AE36F08213B25B5E0EE19425257D0D85 (ok)
File_MD5: Measurement file MD5: AE36F08213B25B5E0EE19425257D0D85 (ok)
File_MD5: Measurement file MD5: AE36F08213B25B5E0EE19425257D0D85 (ok)
File_MD5: Measurement file MD5: AE36F08213B25B5E0EE19425257D0D85 (ok)

Tested on Nokia 5.4 (Android 11)

File_MD5: The right file MD5 -> BCF704DD811A760B5602C20DEDB61AF8

File_MD5: Measurement file MD5: BCF704DD811A760B5602C20DEDB61AF8 (ok)
File_MD5: Measurement file MD5: E65A5D38EB3D8BF4E1AF5240DFBE1840 (ERROR)
File_MD5: Measurement file MD5: BCF704DD811A760B5602C20DEDB61AF8 (ok)
File_MD5: Measurement file MD5: BCF704DD811A760B5602C20DEDB61AF8 (ok)
File_MD5: Measurement file MD5: BCF704DD811A760B5602C20DEDB61AF8 (ok)
File_MD5: Measurement file MD5: BCF704DD811A760B5602C20DEDB61AF8 (ok)
File_MD5: Measurement file MD5: 0D3A577631A115FBAF3324A9B09244A8 (ERROR)
File_MD5: Measurement file MD5: A6FB1334D7AA1520F105ACB1EC1324C5 (ERROR)
File_MD5: Measurement file MD5: BCF704DD811A760B5602C20DEDB61AF8 (ok)
File_MD5: Measurement file MD5: BCF704DD811A760B5602C20DEDB61AF8 (ok)

I'm absolutely standing incomprehensibly in front of this issue, yet another one of Android's fragmented and unreliable ecosystem.

I've tried the following:

Setting my BluetoothGatt instance to CONNECTION_PRIORITY_HIGH mode with requestConnectionPriority

Using a synchronized data container in onCharacteristicChanged in case if this is some multiple thread writing the same container type of error.

None of them helped.

Any insights?

E D I T:

My coworker made a firmware which simply sends incrementing numbers. As you can see within the red area, the data is corrupted, even with Nordic's own nRF toolbox app.

Should I be worried?

That means this Nokia is just doesn't work and that is it? Can this be a hardware issue for only this device?


问:
Why does this code Fail once i add validation in laravel 8?
I am just starting to learn Laravel and I am a little lost here. This code works without validation.

The task is to build a website with user registration Posting data to an already existing database. As I have pointed, without validation it works just fine but when i add validation it fails.

```<code>
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Member;

class RegController extends Controller
{
    public function store(Request $request) {

        Member::create([

        'fname' => $request ->fname,
        'lname' => $request ->lname,
        'gender' => $request ->gender,
        'msisdn' => $request ->msisdn,
        'email' => $request ->email,
        'status' => $request ->mstatus,
        'no_of_children' => $request ->kids,
        'occupation' => $request ->profession,
        'age' => $request ->age,
        'bna' => $request ->bna,
        'residence' => $request ->residence,
        ]);

        return redirect('/members/register');

       }
}
</code>```

But this doesn't...

```<code>
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Member;

class RegController extends Controller
{
    public function store(Request $request) {

        $request->validate([
            'fname' => 'required',
            'lname' => 'required',
            'gender' => 'required',
            'msisdn' => 'required|unique:members_tbl',
            'email' => 'required|unique:members_tbl',
            'status' => 'required',
            'kids' => 'required',
            'profession' => 'required',
            'age' => 'required',
            'bna' => 'required',
            'residence' => 'required',
        ],
        [
            'fname.required' => 'Please Enter your First Name',
            'lname.required' => 'Please Enter your Last Name',
            'gender.required' => 'Please Enter your Gender',
            'msisdn.required' => 'Please Enter your Phone Number',
            'msisdn.unique' => 'A user has already registered with the phone Number',
            'email.unique' => 'A user has already registered with the email',
            'email.required' => 'Please enter a valid email address',
            'status.required' => 'Please Let us know your marital status',
            'kids.required' => 'Please fill out this field',
            'profession.required' => 'Please fill out this field',
            'age.required' => 'Please fill out this field',
            'bna.required' => 'Please fill out this field',
            'residence.required' => 'Please let us know where you live',
        ]);

        Member::create([

        'fname' => $request ->fname,
        'lname' => $request ->lname,
        'gender' => $request ->gender,
        'msisdn' => $request ->msisdn,
        'email' => $request ->email,
        'status' => $request ->mstatus,
        'no_of_children' => $request ->kids,
        'occupation' => $request ->profession,
        'age' => $request ->age,
        'bna' => $request ->bna,
        'residence' => $request ->residence,
        ]);

        return redirect('/members/register');

       }
}

</code>```

What am i missing? The code works well without the validation but just redirects back to the form when validation is added.

Here is my Model

```<code><?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Member extends Model
{
    use HasFactory;

    public $timestamps = false;

    protected $table="members_tbl";

    protected $fillable =[
        'fname',
        'lname',
        'gender',
        'msisdn',
        'email',
        'status',
        'no_of_children',
        'occupation',
        'age',
        'bna',
        'residence'
    ];
}
</code>```

This is the result of var_dump($request)

```<code> public 'request' =>
    object(Symfony\Component\HttpFoundation\InputBag)[44]
      protected 'parameters' =>
        array (size=13)
          '_token' => string 'DuNeITGaDF9K7eEMmU4HwX7nVLJUYDaZ1iYGT4dw' (length=40)
          'fname' => string 'Joe' (length=3)
          'lname' => string 'Peski' (length=5)
          'gender' => string 'male' (length=4)
          'msisdn' => string '254722000001' (length=12)
          'email' => string 'joetry@hotmail.com' (length=18)
          'residence' => string 'New Place' (length=9)
          'age' => string 'teen' (length=4)
          'bna' => string 'no' (length=2)
          'mstatus' => string 'single' (length=6)
          'kids' => string '4' (length=1)
          'profession' => string 'IT' (length=2)
          'submit' => string 'Submit' (length=6)
</code>```

答:
I believe it's working as intended.  If you are not repopulating the fields with the old values then it looks like the page just gets redirected.  Also you need to display the validation messages on the page.

https://laravel.com/docs/8.x/validation#repopulating-forms

https://laravel.com/docs/8.x/validation#quick-displaying-the-validation-errors

Body:
I am just starting to learn Laravel and I am a little lost here. This code works without validation.

The task is to build a website with user registration Posting data to an already existing database. As I have pointed, without validation it works just fine but when i add validation it fails.

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Member;

class RegController extends Controller
{
    public function store(Request $request) {

        Member::create([

        'fname' => $request ->fname,
        'lname' => $request ->lname,
        'gender' => $request ->gender,
        'msisdn' => $request ->msisdn,
        'email' => $request ->email,
        'status' => $request ->mstatus,
        'no_of_children' => $request ->kids,
        'occupation' => $request ->profession,
        'age' => $request ->age,
        'bna' => $request ->bna,
        'residence' => $request ->residence,
        ]);

        return redirect('/members/register');

       }
}

But this doesn't...

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Member;

class RegController extends Controller
{
    public function store(Request $request) {

        $request->validate([
            'fname' => 'required',
            'lname' => 'required',
            'gender' => 'required',
            'msisdn' => 'required|unique:members_tbl',
            'email' => 'required|unique:members_tbl',
            'status' => 'required',
            'kids' => 'required',
            'profession' => 'required',
            'age' => 'required',
            'bna' => 'required',
            'residence' => 'required',
        ],
        [
            'fname.required' => 'Please Enter your First Name',
            'lname.required' => 'Please Enter your Last Name',
            'gender.required' => 'Please Enter your Gender',
            'msisdn.required' => 'Please Enter your Phone Number',
            'msisdn.unique' => 'A user has already registered with the phone Number',
            'email.unique' => 'A user has already registered with the email',
            'email.required' => 'Please enter a valid email address',
            'status.required' => 'Please Let us know your marital status',
            'kids.required' => 'Please fill out this field',
            'profession.required' => 'Please fill out this field',
            'age.required' => 'Please fill out this field',
            'bna.required' => 'Please fill out this field',
            'residence.required' => 'Please let us know where you live',
        ]);

        Member::create([

        'fname' => $request ->fname,
        'lname' => $request ->lname,
        'gender' => $request ->gender,
        'msisdn' => $request ->msisdn,
        'email' => $request ->email,
        'status' => $request ->mstatus,
        'no_of_children' => $request ->kids,
        'occupation' => $request ->profession,
        'age' => $request ->age,
        'bna' => $request ->bna,
        'residence' => $request ->residence,
        ]);

        return redirect('/members/register');

       }
}

What am i missing? The code works well without the validation but just redirects back to the form when validation is added.

Here is my Model

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Member extends Model
{
    use HasFactory;

    public $timestamps = false;

    protected $table="members_tbl";

    protected $fillable =[
        'fname',
        'lname',
        'gender',
        'msisdn',
        'email',
        'status',
        'no_of_children',
        'occupation',
        'age',
        'bna',
        'residence'
    ];
}

This is the result of var_dump($request)

 public 'request' =>
    object(Symfony\Component\HttpFoundation\InputBag)[44]
      protected 'parameters' =>
        array (size=13)
          '_token' => string 'DuNeITGaDF9K7eEMmU4HwX7nVLJUYDaZ1iYGT4dw' (length=40)
          'fname' => string 'Joe' (length=3)
          'lname' => string 'Peski' (length=5)
          'gender' => string 'male' (length=4)
          'msisdn' => string '254722000001' (length=12)
          'email' => string 'joetry@hotmail.com' (length=18)
          'residence' => string 'New Place' (length=9)
          'age' => string 'teen' (length=4)
          'bna' => string 'no' (length=2)
          'mstatus' => string 'single' (length=6)
          'kids' => string '4' (length=1)
          'profession' => string 'IT' (length=2)
          'submit' => string 'Submit' (length=6)